package hotel.switchs.oversea.online.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import hotel.base.oversea.constant.CommonConstants;
import hotel.base.oversea.constant.CommonUrlConstants;
import hotel.base.oversea.constant.SwitchConstants;
import hotel.base.oversea.constant.enums.CommonEnums;
import hotel.base.oversea.constant.enums.MessageEnums;
import hotel.base.oversea.constant.enums.MtHotelEnums;
import hotel.base.oversea.constant.enums.SwitchOrderPoolStateEnums;
import hotel.base.oversea.constant.quartz.UrlSwitchsEnums;
import hotel.base.oversea.dto.switchs.SwitchOrderInfoDto;
import hotel.base.oversea.entity.SwitchsPoolOrderStateHistory;
import hotel.base.oversea.service.impl.BaseServiceImpl;
import hotel.base.oversea.utils.*;
import hotel.base.oversea.vo.ResultStatusInfoVo;
import hotel.base.oversea.vo.meituan.MtHotelOrderJobDealVo;
import hotel.base.oversea.vo.meituan.request.order.MtHotelOrderCheckParamVo;
import hotel.base.oversea.vo.meituan.response.order.MtHotelOrderCheckPricesVo;
import hotel.base.oversea.vo.meituan.response.order.MtHotelOrderCheckVo;
import hotel.switchs.oversea.api.VO.order.OperateDltOrder;
import hotel.switchs.oversea.api.VO.order.ReturnDltOrderInfoCheckVo;
import hotel.switchs.oversea.api.VO.order.ReturnDltOrderInfoVo;
import hotel.switchs.oversea.api.VO.order.SwitchOrderInfoVo;
import hotel.switchs.oversea.api.VO.order.orderDetail.*;
import hotel.switchs.oversea.api.VO.request.*;
import hotel.switchs.oversea.api.VO.request.orderIssue.ArrivalRoomVo;
import hotel.switchs.oversea.api.VO.request.orderIssue.ContactsVo;
import hotel.switchs.oversea.api.VO.request.orderIssue.HotelAndRoomStaticVo;
import hotel.switchs.oversea.api.VO.request.orderIssue.IssueOrderVo;
import hotel.switchs.oversea.api.dto.SwitchCreateRoomDto;
import hotel.switchs.oversea.api.entity.SwitchMasterHotelInfo;
import hotel.switchs.oversea.api.entity.order.*;
import hotel.switchs.oversea.api.entity.order.issue.*;
import hotel.switchs.oversea.online.config.service.RedisService;
import hotel.switchs.oversea.online.mapper.*;
import hotel.switchs.oversea.online.service.*;
import hotel.switchs.oversea.online.utils.SwitchsHttpUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.web.client.RestTemplate;
import tk.mybatis.mapper.entity.Example;

import java.math.BigDecimal;
import java.util.*;

/**
 * @Description: 携程订单
 * @Author: Zhang·jz
 * @date: 2020/6/8
 */
@Slf4j
@Service
public class SwitchOrderInfoServiceImpl extends BaseServiceImpl<SwitchOrderInfo> implements SwitchOrderInfoService {

    @Value("${profile.type}")
    private String profile;

    @Autowired
    private SwitchRestTempaleUtilsService switchRestTempaleUtilsService;

    @Autowired
    private SwitchOrderInfoMapper switchOrderInfoMapper;

    @Autowired
    private SwitchsPoolOrderStateHistoryMapper switchsPoolOrderStateHistoryMapper;

    //关联订单
    @Autowired
    private SwitchOrderReleationMapper switchOrderReleationMapper;

    //订单取消规则
    @Autowired
    private SwitchOrderCancelRulesMapper switchOrderCancelRulesMapper;

    //附加服务
    @Autowired
    private SwitchOrderAdditionalMapper switchOrderAdditionalMapper;

    //采购单信息
    @Autowired
    private SwitchOrderDltissueMapper switchOrderDltissueMapper;

    //每日采购价列表 采购单信息子表
    @Autowired
    private SwitchOrderRoomPurchasePriceMapper switchOrderRoomPurchasePriceMapper;


    //订单优惠信息
    @Autowired
    private SwitchOrderDltPromotionTypesMapper switchOrderDltPromotionTypesMapper;

    //订单扣款信息表
    @Autowired
    private SwitchOrderLadderDeductPoliceMapper switchOrderLadderDeductPoliceMapper;

    //每日房价
    @Autowired
    private SwitchOrderRoomPriceMapper switchOrderRoomPriceMapper;

    //订单每日优惠信息
    @Autowired
    private SwitchOrderEveryDayPromotionsMapper switchOrderEveryDayPromotionsMapper;


    //携程订单变更
    @Autowired
    private SwitchOrderListNotifyMapper switchOrderListNotifyMapper;


    @Autowired
    private RedisService redisService;

    //携程订单池
    @Autowired
    private SwitchOrderPoolMapper switchOrderPoolMapper;

    @Autowired
    private SwitchCreateRoomService switchCreateRoomService;

    @Autowired
    private SwitchOrderPoolService switchOrderPoolService;

    @Autowired
    private RestTemplate restTemplate;


    //发单相关 主表
    @Autowired
    private SwitchIssueOrderMapper switchIssueOrderMapper;

    //订单发单每日房价
    @Autowired
    private SwitchIssueArrivalRoomMapper switchIssueArrivalRoomMapper;

    //订单对应静态信息
    @Autowired
    private SwitchIssueHotelAndRoomStaticMapper switchIssueHotelAndRoomStaticMapper;

    //接单人信息
    @Autowired
    private SwitchIssueReceiverInfoMapper switchIssueReceiverInfoMapper;

    //发单人信息
    @Autowired
    private SwitchIssueSenderInfoMapper switchIssueSenderInfoMapper;

    //母酒店信息
    @Autowired
    private SwitchMasterHotelInfoMapper switchMasterHotelInfoMapper;



    //调用订单校验接口所需参数
    private String hotelId;//酒店id
    private String roomId;//房型id
    private String time;//入住日期格式
    private String endTime;//离店日期格式
    private double price;//价格
    private int num;//房间数

    private String formType;//订单类型

    //推送房型
    @Autowired
    private SwitchPushRoomService switchPushRoomService;

    @Autowired
    private SwitchOrderOperateService switchOrderOperateService;

    //获取token
   // private String token = HttpClientBaseAuth.getAuthToken();

    /**
     * 测试赋值
     * @return
     */
    public List<ReturnDltOrderInfoVo> getReturnDltOrderInfoVos(){
        List<ReturnDltOrderInfoVo> returnDltOrderInfoVoList = new ArrayList<>();
        List<SwitchOrderListNotify> switchOrderListNotifyList = switchOrderListNotifyMapper.selectAll();
        if(!switchOrderListNotifyList.isEmpty()){
            switchOrderListNotifyList.forEach(switchOrderListNotify->{
                ReturnDltOrderInfoVo returnDltOrderInfoVo = new ReturnDltOrderInfoVo();
                returnDltOrderInfoVo.setDltOrderId(switchOrderListNotify.getDltOrderId());
                returnDltOrderInfoVo.setOrderId(switchOrderListNotify.getOrderId());
                returnDltOrderInfoVo.setChannel(switchOrderListNotify.getChannel());
                returnDltOrderInfoVo.setChildChannel(switchOrderListNotify.getChildChannel());
                returnDltOrderInfoVo.setUpdateTime(switchOrderListNotify.getUpdateTime());
                returnDltOrderInfoVo.setOrderDate(switchOrderListNotify.getOrderDate());
                returnDltOrderInfoVo.setFormType(switchOrderListNotify.getFormType());
                returnDltOrderInfoVo.setOrderStatus(switchOrderListNotify.getOrderStatus());
                returnDltOrderInfoVo.setCheckinDate(switchOrderListNotify.getCheckinDate());
                returnDltOrderInfoVo.setCheckoutDate(switchOrderListNotify.getCheckoutDate());
                returnDltOrderInfoVo.setMd5Key(switchOrderListNotify.getMd5Key());

                returnDltOrderInfoVoList.add(returnDltOrderInfoVo);
            });
        }


        return returnDltOrderInfoVoList;
    }

    /**
     * 订单变化通知接口
     * 注：每分钟调用不得超过 10 次，分页获取
     * 注：获取新订单
     * 定时任务建议8s调用一次
     *
     * @param requestOrderMotifyVO
     * @return
     */
    @Override
    public Result<Object> getdltordernotify(RequestOrderMotifyVo requestOrderMotifyVO) {
        //获取订单相关信息
        Map<String, Object> data = new HashMap<>();

        data.put("startTime", requestOrderMotifyVO.getStartTime());
        data.put("endTime", requestOrderMotifyVO.getEndTime());
        data.put("channel", requestOrderMotifyVO.getChannels());
        data.put("formType", requestOrderMotifyVO.getFormType());
        data.put("orderStatus", requestOrderMotifyVO.getOrderStatus());
        data.put("hotelId", requestOrderMotifyVO.getHotelIds());
        Map pagingType = new HashMap();
        pagingType.put("pageSize", requestOrderMotifyVO.getPageSize());
        pagingType.put("pageIndex", requestOrderMotifyVO.getPageIndex());
        data.put("pagingType", pagingType);

        String result = SwitchsHttpUtils.sendRequest(data, SwitchConstants.SWITCH_API_GET_DLT_ORDER_MOTIFY, profile);
        //对结构进行格式化
        Map<String,Object> map = JacksonUtil.parse(result,Map.class);

        log.info("getdltordernotify=map --- >>>>>>>>{} ",map);
        ResultStatusInfoVo resultStatusInfoVo = JacksonUtil.parse(JacksonUtil.objectToJson(map.get("resultStatus")), ResultStatusInfoVo.class);
        //说明调用接口失败 <除了 0 是正确，别的都是错误>
        if (resultStatusInfoVo.getResultCode() != 0) {
            log.info("getdltordernotify  订单变化通知接口-调用接口失败{}", resultStatusInfoVo);
            return new Result<>(JacksonUtil.objectToJson(resultStatusInfoVo.getResultMsg()), CommonConstants.REQUEST_ERROR);
        }

        //解析返回值，并转为对应vo输出
        List<ReturnDltOrderInfoVo> returnDltOrderInfoVo = new ArrayList<>();

        if(!map.containsKey("dltOrderList")) {
            log.info("getdltordernotify   JacksonUtil.objectToJson(map.get('dltOrderList')) --- 数据为空>>>>>>>>");
            return new Result<>(CommonEnums.DATA_NULL);
        }else{
            returnDltOrderInfoVo = JacksonUtil.jsonToList(JacksonUtil.objectToJson(map.get("dltOrderList")), ReturnDltOrderInfoVo.class);
        }

        log.info("getdltordernotify   returnDltOrderInfoVo --- >>>>>>>>{} ",returnDltOrderInfoVo);
        //////////////单元测试////////////////
//        List<ReturnDltOrderInfoVo> returnDltOrderInfoVo = getReturnDltOrderInfoVos();
        //////////////////////////////

        //遍历新订单信息
        if (!ObjectUtils.isEmpty(returnDltOrderInfoVo) && returnDltOrderInfoVo.size() > 0) {
            for (ReturnDltOrderInfoVo dltOrderInfoVo : returnDltOrderInfoVo) {
                if (!ObjectUtils.isEmpty(dltOrderInfoVo) && !ObjectUtils.isEmpty(dltOrderInfoVo.getMd5Key())) {
                    //根据关键属性唯一验证，可根据各自场景来判断是否重复拉取
                    //放入redis缓存，并做相关数据处理
                    //如存在相关未处理新订单，直接做相关key替换
//                    operationSwitchOrderListNotify(dltOrderInfoVo);

                    ///////////////////2020-09-14 start////////////////////////
                    //判断是否操作成功
                    SwitchOrderListNotify switchOrderListNotifyResult =  operationSwitchOrderListNotifyNew(dltOrderInfoVo);
                    ////////////////////2020-09-14 end///////////////////////
                }
            }

        }
        return new Result<>(returnDltOrderInfoVo);
    }

    //保证表中订单数据的唯一性 -- 可作为订单读取历史表  做为线上订单池2020-09-14
    public synchronized SwitchOrderListNotify operationSwitchOrderListNotifyNew(ReturnDltOrderInfoVo dltOrderInfoVo) {
        boolean ret = false;
        //0 待操作 其他不操作
        int isDeal = 0;
        //存储至对应表 可做订单拉取日志记录表
        SwitchOrderListNotify switchOrderListNotify = new SwitchOrderListNotify();

        //系统字段
        switchOrderListNotify.setId(StringUtil.getUUID());
        switchOrderListNotify.setState(0);//默认正常
        switchOrderListNotify.setSysOrderState(0);//默认系统订单状态 0：正常 ；1：以处理 2：校验通过
        switchOrderListNotify.setCreateTime(new Date());
        switchOrderListNotify.setModifyTime(new Date());
        //接口返回字段
        switchOrderListNotify.setChannel(dltOrderInfoVo.getChannel());
        switchOrderListNotify.setChildChannel(dltOrderInfoVo.getChildChannel());
        switchOrderListNotify.setCheckinDate(dltOrderInfoVo.getCheckinDate());
        switchOrderListNotify.setCheckoutDate(dltOrderInfoVo.getCheckoutDate());
        switchOrderListNotify.setDltOrderId(dltOrderInfoVo.getDltOrderId());
        switchOrderListNotify.setMd5Key(dltOrderInfoVo.getMd5Key());
        switchOrderListNotify.setOrderDate(dltOrderInfoVo.getOrderDate());
        switchOrderListNotify.setUpdateTime(dltOrderInfoVo.getUpdateTime());

        /**
         *@Description: 根据订单id ，订单类型， 订单状态 判断是否存在
         *@Author: Zhang·jz
         *@date: 2020/9/3
         */
        switchOrderListNotify.setOrderId(dltOrderInfoVo.getOrderId());
        switchOrderListNotify.setFormType(dltOrderInfoVo.getFormType());
        switchOrderListNotify.setOrderStatus(dltOrderInfoVo.getOrderStatus());

        //判断订单类型是否为空,直接不做操作！
        if(ObjectUtils.isEmpty(dltOrderInfoVo.getFormType())){
            return  null;
        }

        int hasOrder = 0;
        //携程无效订单
        if("T".equals(dltOrderInfoVo.getFormType())){
            isDeal = 10;
            switchOrderListNotify.setIsDealRemark("当前订单id("+dltOrderInfoVo.getOrderId()+") ，订单类型:"+dltOrderInfoVo.getFormType()+"， 订单状态:"+dltOrderInfoVo.getOrderStatus()+"; 无效订单不处理！");
        }else {
            //携程未操作订单（新订单、取消订单）
            if ("0".equals(dltOrderInfoVo.getOrderStatus())) {
                Map map = new HashMap();
                map.put("orderId", dltOrderInfoVo.getOrderId());
                map.put("formType", dltOrderInfoVo.getFormType());
                map.put("orderStatus", dltOrderInfoVo.getOrderStatus());
                hasOrder = switchOrderListNotifyMapper.countNotifyOrderByOrderIdStateType(map);
                //如果存在相同则不操作,如果存在SMS订单，则可以不操作该条订单
                if (hasOrder > 0 && "SMS".equals(dltOrderInfoVo.getChannel())) {
                    isDeal = 10;
                    switchOrderListNotify.setIsDealRemark("当前订单id(" + dltOrderInfoVo.getOrderId() + ") ，订单类型:" + dltOrderInfoVo.getFormType() + "， 订单状态:" + dltOrderInfoVo.getOrderStatus() + "; 可能存在不同渠道通知新订单，当前操作不处理！");
                }
            }else {
                isDeal = 10;
                switchOrderListNotify.setIsDealRemark("当前订单id(" + dltOrderInfoVo.getOrderId() + ") ，订单类型:" + dltOrderInfoVo.getFormType() + "， 订单状态:" + dltOrderInfoVo.getOrderStatus() + "; 携程通知已处理，当前操作不做流程处理 ！");
            }
        }
        switchOrderListNotify.setIsDeal(isDeal);
        ///////////2020/9/3 --end////////////

        int retInt = 0;
        //新增,订单不为空 md5key 包含订单等相关信息，可以作为判断是否有订单
        log.info("根据 md5_key 删除对应 表中数据：{}", dltOrderInfoVo.getMd5Key());
        SwitchOrderListNotify switchOrderListNotifyOld = new SwitchOrderListNotify();
        switchOrderListNotifyOld = switchOrderListNotifyMapper.findSwitchOrderListNotifyByMd5Key(dltOrderInfoVo.getMd5Key());

        //不为空则更新
        if (!ObjectUtils.isEmpty(switchOrderListNotifyOld) && !ObjectUtils.isEmpty(switchOrderListNotifyOld.getId())) {
            log.info("将拉取的订单信息，更新至对应表(switch_order_list_notify)-:{}", switchOrderListNotify);
            switchOrderListNotify.setId(switchOrderListNotifyOld.getId());
            switchOrderListNotify.setCreateTime(switchOrderListNotifyOld.getCreateTime());
            retInt = switchOrderListNotifyMapper.updateByPrimaryKey(switchOrderListNotify);
            log.info("将拉取的订单信息，更新至对应表(switch_order_list_notify)-成功更新" + retInt + "条数据");
        } else {//否则新增


            //订单是否成功
            String remarkStr = "";
            if(isDeal == 10 && "100".equals(dltOrderInfoVo.getOrderStatus())){
                //携程操作成功（新增、取消、修改订单） 2020-09-23 新增
                if(("N".equals(dltOrderInfoVo.getFormType()) || "C".equals(dltOrderInfoVo.getFormType()) || "M".equals(dltOrderInfoVo.getFormType()))){
                    //推送消息至钉钉群
                    try {
                        Thread dingMessage=new ThreadDingMessage(switchOrderListNotify);
                        dingMessage.start();
                    }catch (Exception e){
                        log.info("钉钉推送异常，请检查！");
                    }
                    SwitchOrderPool switchOrderPool = new SwitchOrderPool();
                    switchOrderPool = switchOrderPoolMapper.findOrderBySwitchOrderId(dltOrderInfoVo.getOrderId());
                    //美团未接单，携程人工操作；将订单池状态修改为 订单状态：12；延时状态：1（不延时）
                    if(!ObjectUtils.isEmpty(switchOrderPool) && "0".equals(switchOrderPool.getMtOrderState())){
                        switchOrderPool.setRemark(switchOrderPool.getRemark()+"; "+DateUtil.getNowTime()+" 人工操作携程后台订单状态:12 ");
                        switchOrderPool.setSysOrderState(12);//人工操作
                        switchOrderPool.setIsOrder(1);//修改立即
                        int updInt = switchOrderPoolMapper.updateOrderStateByPK(switchOrderPool);
                        if(updInt != -1){
                            remarkStr = "; 操作订单池："+DateUtil.getNowTime()+" 美团未接单，携程人工操作；将订单池状态修改为 订单状态：12；延时状态：1（不延时）";
                        }
                    }

                }

                switchOrderListNotify.setIsDealRemark(switchOrderListNotify.getIsDealRemark()+ remarkStr);
            }
            log.info("将拉取的订单信息，新增至对应表(switch_order_list_notify)-:{}", switchOrderListNotify);
            retInt = switchOrderListNotifyMapper.insert(switchOrderListNotify);
            log.info("将拉取的订单信息，新增至对应表(switch_order_list_notify)-成功新增" + retInt + "条数据");


            //携程新订单
            if(retInt != -1 && isDeal == 0){
                //推送消息至钉钉群
                try {
                    Thread dingMessage=new ThreadDingMessage(switchOrderListNotify);
                    dingMessage.start();
                }catch (Exception e){
                    log.info("钉钉推送异常，请检查！");
                }
                //订单状态未 0 未操作； 渠道不为 SMS
                if(!ObjectUtils.isEmpty(switchOrderListNotify) &&  "0".equals(switchOrderListNotify.getOrderStatus()) &&  switchOrderListNotify.getIsDeal() == 0){
                    operateSwitchAndMeituanOrderByOrderId(dltOrderInfoVo.getMd5Key());
                }
            }
        }

        //数据库操作成功
        if(retInt != -1){
            ret = true;
        }
        return switchOrderListNotify;
    }

    //保证表中订单数据的唯一性 -- 可作为订单读取历史表  做为线上订单池
    public void operationSwitchOrderListNotify(ReturnDltOrderInfoVo dltOrderInfoVo) {
        //0 待操作 其他不操作
        int isDeal = 0;
        //存储至对应表 可做订单拉取日志记录表
        SwitchOrderListNotify switchOrderListNotify = new SwitchOrderListNotify();

        //系统字段
        switchOrderListNotify.setId(StringUtil.getUUID());
        switchOrderListNotify.setState(0);//默认正常
        switchOrderListNotify.setSysOrderState(0);//默认系统订单状态 0：正常 ；1：以处理 2：校验通过
        switchOrderListNotify.setCreateTime(new Date());
        switchOrderListNotify.setModifyTime(new Date());
        //接口返回字段
        switchOrderListNotify.setChannel(dltOrderInfoVo.getChannel());
        switchOrderListNotify.setChildChannel(dltOrderInfoVo.getChildChannel());
        switchOrderListNotify.setCheckinDate(dltOrderInfoVo.getCheckinDate());
        switchOrderListNotify.setCheckoutDate(dltOrderInfoVo.getCheckoutDate());
        switchOrderListNotify.setDltOrderId(dltOrderInfoVo.getDltOrderId());
        switchOrderListNotify.setMd5Key(dltOrderInfoVo.getMd5Key());
        switchOrderListNotify.setOrderDate(dltOrderInfoVo.getOrderDate());
        switchOrderListNotify.setUpdateTime(dltOrderInfoVo.getUpdateTime());

        /**
         *@Description: 根据订单id ，订单类型， 订单状态 判断是否存在
         *@Author: Zhang·jz
         *@date: 2020/9/3
         */
        switchOrderListNotify.setOrderId(dltOrderInfoVo.getOrderId());
        switchOrderListNotify.setFormType(dltOrderInfoVo.getFormType());
        switchOrderListNotify.setOrderStatus(dltOrderInfoVo.getOrderStatus());

        int hasOrder = 0;
        //携程未操作订单（新订单、取消订单）
        if("0".equals(dltOrderInfoVo.getOrderStatus())){
            Map map = new HashMap();
            map.put("orderId",dltOrderInfoVo.getOrderId());
            map.put("formType",dltOrderInfoVo.getFormType());
            map.put("orderStatus",dltOrderInfoVo.getOrderStatus());
            hasOrder = switchOrderListNotifyMapper.countNotifyOrderByOrderIdStateType(map);
            //如果存在相同则不操作,如果存在SMS订单，则可以不操作该条订单
            if(hasOrder > 0 && "SMS".equals(dltOrderInfoVo.getChannel())){
                isDeal = 10;
                switchOrderListNotify.setIsDealRemark("当前订单id("+dltOrderInfoVo.getOrderId()+") ，订单类型:"+dltOrderInfoVo.getFormType()+"， 订单状态:"+dltOrderInfoVo.getOrderStatus()+"; 可能存在不同渠道通知新订单，当前操作不处理！");
            }
        }else{
            isDeal = 10;
            switchOrderListNotify.setIsDealRemark("当前订单id("+dltOrderInfoVo.getOrderId()+") ，订单类型:"+dltOrderInfoVo.getFormType()+"， 订单状态:"+dltOrderInfoVo.getOrderStatus()+"; 携程通知已处理，当前操作不处理！");
        }

        switchOrderListNotify.setIsDeal(isDeal);
        ///////////2020/9/3 --end////////////

        int retInt = 0;
        //新增,订单不为空 md5key 包含订单等相关信息，可以作为判断是否有订单
        log.info("根据 md5_key 删除对应 表中数据：{}", dltOrderInfoVo.getMd5Key());
        SwitchOrderListNotify switchOrderListNotifyOld = new SwitchOrderListNotify();
        switchOrderListNotifyOld = switchOrderListNotifyMapper.findSwitchOrderListNotifyByMd5Key(dltOrderInfoVo.getMd5Key());

        //不为空则更新
        if (!ObjectUtils.isEmpty(switchOrderListNotifyOld) && !ObjectUtils.isEmpty(switchOrderListNotifyOld.getId())) {
            log.info("将拉取的订单信息，更新至对应表(switch_order_list_notify)-:{}", switchOrderListNotify);
            switchOrderListNotify.setId(switchOrderListNotifyOld.getId());
            switchOrderListNotify.setCreateTime(switchOrderListNotifyOld.getCreateTime());
            retInt = switchOrderListNotifyMapper.updateByPrimaryKey(switchOrderListNotify);
            log.info("将拉取的订单信息，更新至对应表(switch_order_list_notify)-成功更新" + retInt + "条数据");
        } else {//否则新增
            log.info("将拉取的订单信息，新增至对应表(switch_order_list_notify)-:{}", switchOrderListNotify);
            retInt = switchOrderListNotifyMapper.insert(switchOrderListNotify);
            log.info("将拉取的订单信息，新增至对应表(switch_order_list_notify)-成功新增" + retInt + "条数据");

            if(retInt != -1 && isDeal == 0){
                //推送消息至钉钉群
                try {
                    Thread dingMessage=new ThreadDingMessage(switchOrderListNotify);
                    dingMessage.start();
                }catch (Exception e){
                    log.info("钉钉推送异常，请检查！");
                }
            }
        }

    }


    /**
     * 订单详情接口
     * 注：每分钟调用不得超过 10 次
     * 每次只能查询一个订单
     *
     * @param dltOrderId
     * @return
     */
    @Override
    @Retryable(value = Exception.class, maxAttempts = 4, backoff = @Backoff(delay = 2000, multiplier = 1.5))
    public Result<Object> getdltorderinfo(String dltOrderId) {
        //获取订单相关信息
        Map<String, Object> data = new HashMap<>();

        data.put("dltOrderId", dltOrderId);

        String result = SwitchsHttpUtils.sendRequest(data, SwitchConstants.SWITCH_API_GET_DLT_ORDER_INFO, profile);
        //对结构进行格式化
//        JSONObject jsonObject = JSONObject.fromObject(result);
//        ResultStatusInfoVo resultStatusInfoVo = JSONUtils.toBean(jsonObject.getJSONObject("resultStatus"), ResultStatusInfoVo.class);

        Map<String,Object> map = JacksonUtil.parse(result,Map.class);
        ResultStatusInfoVo resultStatusInfoVo = JacksonUtil.parse(JacksonUtil.objectToJson(map.get("resultStatus")), ResultStatusInfoVo.class);
        log.warn("订单详情接口-调用接口返回值：{}",resultStatusInfoVo);
        //判断是否拉取到订单详情 20201124修改，针对拉取到信息失败-携程系统接口异常，不需调整
//        int count = 0;
//        while ((resultStatusInfoVo.getResultCode() != 0) && count <3){
//            getdltorderinfo(dltOrderId);
//            count++;
//        }
        //说明调用接口失败 <除了 0 是正确，别的都是错误>
        if (resultStatusInfoVo.getResultCode() != 0 || !map.containsKey("dltOrderInfo") || ObjectUtils.isEmpty(map.get("dltOrderInfo"))) { //调用接口异常统一循环3次
//            log.warn("订单详情接口-调用接口失败{}", resultStatusInfoVo);
//            return new Result<>(resultStatusInfoVo.getResultMsg(), CommonConstants.REQUEST_ERROR);
//        }
//
//        if(!map.containsKey("dltOrderInfo")){
//            log.warn("JacksonUtil.objectToJson(map.get('dltOrderInfo')) --- 数据为空>>>>>>>>");
//            return new Result<>(CommonEnums.DATA_NULL);
//        }
//
//        //如果接口调用返回订单信息为null,重试3次-每次停1s 20201127 ZhangJZ
//        if(ObjectUtils.isEmpty(map.get("dltOrderInfo"))){
            log.warn("订单详情接口-调用接口异常！！！getdltorderinfo>>>resultStatusInfoVo>>>{}",resultStatusInfoVo);
            int runCount = 0;
            while (ObjectUtils.isEmpty(map.get("dltOrderInfo")) && runCount < 3){
                try {
                    //停顿1s
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                getdltorderinfo(dltOrderId);
                runCount++;
                log.warn("订单详情接口-调用接口runCount:{}---getdltorderinfo>>>map.get(dltOrderInfo)>>>{}",runCount,map.get("dltOrderInfo"));
            }
        }
        //解析订单信息返回值，并转为对应vo输出
//        ReturnOrderInfo returnOrderInfo = JSONUtils.toBean(jsonObject.getJSONObject("dltOrderInfo"), ReturnOrderInfo.class);
        ReturnOrderInfo returnOrderInfo = JacksonUtil.parse(JacksonUtil.objectToJson(map.get("dltOrderInfo")), ReturnOrderInfo.class);
        log.info("订单信息数据{}", returnOrderInfo);

        boolean retInt = false;

        //读取相关订单详情存入数据库
        if (!ObjectUtils.isEmpty(returnOrderInfo)) {
            retInt = insertOrderInfos(returnOrderInfo);
        }

        return new Result<>(retInt);
    }



    /**
     * 新增订单相关表以及子表
     *
     * @param returnOrderInfo
     * @return boolean
     */
    @Transactional
    public boolean insertOrderInfos(ReturnOrderInfo returnOrderInfo) {
        boolean ret = false;
        //如果存在代理通ID包含SMS的数据，则不做处理 20200903
        if(returnOrderInfo.getDltOrderId().indexOf("SMS") != -1){
            return true;
        }
        String swicthOrderInfoId = StringUtil.getUUID();
        int state = 0;//默认0
        Date createTime = new Date();
        Date modifyTime = new Date();


        //判断当前订单id是否存在订单主表，存在则直接修改主表信息
        SwitchOrderInfo switchOrderInfoComp = new SwitchOrderInfo();
//        switchOrderInfoComp.setOrderId(returnOrderInfo.getOrderId());
//        switchOrderInfoComp = switchOrderInfoMapper.selectOne(switchOrderInfoComp);

        String orderId = returnOrderInfo.getOrderId();//订单id
        Map switchOrderInfoMap = new HashMap();
        switchOrderInfoMap.put("orderId",orderId);
        switchOrderInfoComp = switchOrderInfoMapper.findOneByOrderId(switchOrderInfoMap);
        log.info("insertOrderInfos ---> 根据订单号("+orderId+")获取订单信息-->switchOrderInfo: {}",switchOrderInfoComp);


        //判断是否存在相关酒店数据
        if(!ObjectUtils.isEmpty(switchOrderInfoComp) && ObjectUtils.isEmpty(switchOrderInfoComp.getHotelId())){

            log.info("表中存订单号为："+returnOrderInfo.getOrderId()+"数据；修改订单信息主表-->>>");
            SwitchOrderInfo switchOrderInfo = new SwitchOrderInfo();
            switchOrderInfo = (SwitchOrderInfo) Dto2Entity.populate(returnOrderInfo, switchOrderInfo);
            switchOrderInfo.setId(switchOrderInfoComp.getId());
            switchOrderInfo.setModifyTime(modifyTime);

            //酒店id赋值
            hotelId = switchOrderInfo.getHotelId();
            roomId = switchOrderInfo.getRoomId();
            log.info("switchOrderInfo.getCheckinDate()==",switchOrderInfo.getCheckinDate());
            log.info("switchOrderInfo.getCheckinDate().toString==",switchOrderInfo.getCheckinDate().toString());
            time = DateUtil.switchDateParse(switchOrderInfo.getCheckinDate().toString());
            endTime = DateUtil.switchDateParse(switchOrderInfo.getCheckoutDate().toString());
            price = switchOrderInfo.getOrderPrice().doubleValue();
            num = switchOrderInfo.getRoomnum();



            formType = switchOrderInfo.getFormType();//订单类型

            int soimUpd = switchOrderInfoMapper.updateByPrimaryKey(switchOrderInfo);
            if(soimUpd != -1){
                log.info("修改订单信息主表,订单号为："+returnOrderInfo.getOrderId()+"数据；修改成功！！！");
                ret = true;
            }else{
                log.info("修改订单信息主表,订单号为："+returnOrderInfo.getOrderId()+"数据；修改失败，请查询原因！！！");
            }
            return ret;
        }



        //新增订单信息主表
        log.info("新增订单信息主表-->>>");
        SwitchOrderInfo switchOrderInfo = new SwitchOrderInfo();
        switchOrderInfo = (SwitchOrderInfo) Dto2Entity.populate(returnOrderInfo, switchOrderInfo);
        switchOrderInfo.setId(swicthOrderInfoId);
        switchOrderInfo.setState(state);
        switchOrderInfo.setCreateTime(createTime);
        switchOrderInfo.setModifyTime(modifyTime);

        //酒店id赋值
        hotelId = switchOrderInfo.getHotelId();
        roomId = switchOrderInfo.getRoomId();
        log.info("switchOrderInfo.getCheckinDate()==",switchOrderInfo.getCheckinDate());
        log.info("switchOrderInfo.getCheckinDate().toString==",switchOrderInfo.getCheckinDate().toString());
        time = DateUtil.switchDateParse(switchOrderInfo.getCheckinDate().toString());
        price = switchOrderInfo.getOrderPrice().doubleValue();
        endTime = DateUtil.switchDateParse(switchOrderInfo.getCheckoutDate().toString());
        num = switchOrderInfo.getRoomnum();
        formType = switchOrderInfo.getFormType();//订单类型

        int soimInt = switchOrderInfoMapper.insert(switchOrderInfo);
        if (soimInt != -1) {
            //新增订单子表：关联订单
            log.info("新增订单子表：关联订单--start>>>");
            int sorIntCount = 0;
            SwitchOrderReleation switchOrderReleation = new SwitchOrderReleation();
            ReturnOrderReleation returnOrderReleation = returnOrderInfo.getReleationOrder();
            if(null != returnOrderReleation){
                switchOrderReleation = (SwitchOrderReleation) Dto2Entity.populate(returnOrderReleation, switchOrderReleation);

                switchOrderReleation.setId(StringUtil.getUUID());
                switchOrderReleation.setPId(swicthOrderInfoId);//父级SwitchOrderInfo id
                switchOrderReleation.setState(state);
                switchOrderReleation.setCreateTime(createTime);
                switchOrderReleation.setModifyTime(modifyTime);

                sorIntCount = switchOrderReleationMapper.insert(switchOrderReleation);
                log.info("新增订单子表：关联订单--end>>>成功执行{}条", sorIntCount);
            }else{
                log.info("订单子表：关联订单--null>>>成功执行0条");
            }



            //新增订单子表：订单取消规则
            log.info("新增订单子表：订单取消规则--start>>>");
            List<ReturnOrderCancelRules> cancelRules = returnOrderInfo.getCancelRules();
            if(null != cancelRules){
                List<SwitchOrderCancelRules> switchOrderCancelRulesList = new ArrayList<>();
                int socrlIntCount = 0;
                if (!cancelRules.isEmpty() && cancelRules.size() > 0) {
                    cancelRules.forEach(returnOrderCancelRules -> {
                                SwitchOrderCancelRules switchOrderCancelRules = new SwitchOrderCancelRules();
                                switchOrderCancelRules = (SwitchOrderCancelRules) Dto2Entity.populate(returnOrderCancelRules, switchOrderCancelRules);

                                switchOrderCancelRules.setId(StringUtil.getUUID());
                                switchOrderCancelRules.setPId(swicthOrderInfoId);//父级SwitchOrderInfo id
                                switchOrderCancelRules.setState(state);
                                switchOrderCancelRules.setCreateTime(createTime);
                                switchOrderCancelRules.setModifyTime(modifyTime);

                                switchOrderCancelRulesList.add(switchOrderCancelRules);
                            }
                    );

                    socrlIntCount = switchOrderCancelRulesMapper.insertList(switchOrderCancelRulesList);
                }
                log.info("新增订单子表：订单取消规则--end>>>成功执行{}条", socrlIntCount);
            }else{
                log.info("新增订单子表：订单取消规则--null>>>成功执行0条");
            }



            //新增订单子表：附加服务
            log.info("新增订单子表：附加服务--start>>>");
            List<ReturnOrderAdditional> additionalList = returnOrderInfo.getAdditionalList();
            if(null != additionalList){
                List<SwitchOrderAdditional> switchOrderAdditionalList = new ArrayList<>();
                int soalIntCount = 0;
                if (!additionalList.isEmpty() && additionalList.size() > 0) {
                    additionalList.forEach(returnOrderAdditional -> {
                                SwitchOrderAdditional switchOrderAdditional = new SwitchOrderAdditional();
                                switchOrderAdditional = (SwitchOrderAdditional) Dto2Entity.populate(returnOrderAdditional, switchOrderAdditional);

                                switchOrderAdditional.setId(StringUtil.getUUID());
                                switchOrderAdditional.setPId(swicthOrderInfoId);//父级SwitchOrderInfo id
                                switchOrderAdditional.setState(state);
                                switchOrderAdditional.setCreateTime(createTime);
                                switchOrderAdditional.setModifyTime(modifyTime);

                                switchOrderAdditionalList.add(switchOrderAdditional);
                            }
                    );

                    soalIntCount = switchOrderAdditionalMapper.insertList(switchOrderAdditionalList);
                }
                log.info("新增订单子表：附加服务--end>>>成功执行{}条", soalIntCount);
            }else{
                log.info("新增订单子表：附加服务--null>>>成功执行0条");
            }




            //新增订单子表：采购单信息
            log.info("新增订单子表：采购单信息--start>>>");
            int sodIntCount = 0;
            String orderDltissueId = StringUtil.getUUID();
            SwitchOrderDltissue switchOrderDltissue = new SwitchOrderDltissue();
            if(null != switchOrderDltissue){
                ReturnOrderDltissue dltIssueOrder = returnOrderInfo.getDltIssueOrder();
                switchOrderDltissue = (SwitchOrderDltissue) Dto2Entity.populate(dltIssueOrder, switchOrderDltissue);

                switchOrderDltissue.setId(orderDltissueId);
                switchOrderDltissue.setPId(swicthOrderInfoId);//父级SwitchOrderInfo id
                switchOrderDltissue.setState(state);
                switchOrderDltissue.setCreateTime(createTime);
                switchOrderDltissue.setModifyTime(modifyTime);

                sodIntCount = switchOrderDltissueMapper.insert(switchOrderDltissue);

                if (sodIntCount > 0) {
                    log.info("新增采购单信息子表：每日采购价列表--start>>>");
                    int sorppIntCount = 0;
                    List<ReturnOrderRoomPurchasePrice> roomPurchasePriceList = dltIssueOrder.getRoomPurchasePriceList();
                    List<SwitchOrderRoomPurchasePrice> switchOrderRoomPurchasePriceList = new ArrayList<>();
                    if (!roomPurchasePriceList.isEmpty() && roomPurchasePriceList.size() > 0) {
                        roomPurchasePriceList.forEach(roomPurchasePrice -> {
                                    SwitchOrderRoomPurchasePrice switchOrderRoomPurchasePrice = new SwitchOrderRoomPurchasePrice();
                                    switchOrderRoomPurchasePrice = (SwitchOrderRoomPurchasePrice) Dto2Entity.populate(roomPurchasePrice, switchOrderRoomPurchasePrice);

                                    switchOrderRoomPurchasePrice.setId(StringUtil.getUUID());
                                    switchOrderRoomPurchasePrice.setPId(orderDltissueId);//父级SwitchOrderDltissue id
                                    switchOrderRoomPurchasePrice.setState(state);
                                    switchOrderRoomPurchasePrice.setCreateTime(createTime);
                                    switchOrderRoomPurchasePrice.setModifyTime(modifyTime);

                                    switchOrderRoomPurchasePriceList.add(switchOrderRoomPurchasePrice);
                                }
                        );

                        sorppIntCount = switchOrderRoomPurchasePriceMapper.insertList(switchOrderRoomPurchasePriceList);
                    }
                    log.info("新增采购单信息子表：每日采购价列表--end>>>成功执行{}条", sorppIntCount);
                }

                log.info("新增订单子表：采购单信息--end>>>成功执行{}条", sodIntCount);

            }else{
                log.info("新增订单子表：采购单信息--null>>>成功执行0条");
            }

            //新增订单子表：订单优惠信息
            log.info("新增订单子表：订单优惠信息--start>>>");
            List<ReturnOrderDltPromotionTypes> dltOrderPromotionTypes = returnOrderInfo.getDltOrderPromotionTypes();
            if(null != dltOrderPromotionTypes){
                List<SwitchOrderDltPromotionTypes> switchOrderDltPromotionTypesList = new ArrayList<>();
                int sodptIntCount = 0;
                if (!dltOrderPromotionTypes.isEmpty() && dltOrderPromotionTypes.size() > 0) {
                    dltOrderPromotionTypes.forEach(returnOrderDltPromotionTypes -> {
                                SwitchOrderDltPromotionTypes switchOrderDltPromotionTypes = new SwitchOrderDltPromotionTypes();
                                switchOrderDltPromotionTypes = (SwitchOrderDltPromotionTypes) Dto2Entity.populate(returnOrderDltPromotionTypes, switchOrderDltPromotionTypes);

                                switchOrderDltPromotionTypes.setId(StringUtil.getUUID());
                                switchOrderDltPromotionTypes.setPId(swicthOrderInfoId);//父级SwitchOrderInfo id
                                switchOrderDltPromotionTypes.setState(state);
                                switchOrderDltPromotionTypes.setCreateTime(createTime);
                                switchOrderDltPromotionTypes.setModifyTime(modifyTime);

                                switchOrderDltPromotionTypesList.add(switchOrderDltPromotionTypes);
                            }
                    );

                    sodptIntCount = switchOrderDltPromotionTypesMapper.insertList(switchOrderDltPromotionTypesList);
                }
                log.info("新增订单子表：订单优惠信息--end>>>成功执行{}条", sodptIntCount);
            }else{
                log.info("新增订单子表：订单优惠信息--null>>>成功执行0条");
            }


            //新增订单子表：每日房价列表
            log.info("新增订单子表：每日房价列表--start>>>");
            List<ReturnOrderRoomPrice> roomPriceList = returnOrderInfo.getRoomPriceList();
            if(null != roomPriceList){
                List<SwitchOrderRoomPrice> switchOrderRoomPriceList = new ArrayList<>();
                int sorpIntCount = 0;
                if (!roomPriceList.isEmpty() && roomPriceList.size() > 0) {
                    roomPriceList.forEach(returnOrderRoomPrice -> {
                                SwitchOrderRoomPrice switchOrderRoomPrice = new SwitchOrderRoomPrice();
                                switchOrderRoomPrice = (SwitchOrderRoomPrice) Dto2Entity.populate(returnOrderRoomPrice, switchOrderRoomPrice);

                                switchOrderRoomPrice.setId(StringUtil.getUUID());
                                switchOrderRoomPrice.setPId(swicthOrderInfoId);//父级SwitchOrderInfo id
                                switchOrderRoomPrice.setState(state);
                                switchOrderRoomPrice.setCreateTime(createTime);
                                switchOrderRoomPrice.setModifyTime(modifyTime);

                                switchOrderRoomPriceList.add(switchOrderRoomPrice);
                            }
                    );

                    sorpIntCount = switchOrderRoomPriceMapper.insertList(switchOrderRoomPriceList);
                }
                log.info("新增订单子表：每日房价列表--end>>>成功执行{}条", sorpIntCount);
            }else{
                log.info("新增订单子表：每日房价列表--null>>>成功执行0条");
            }


            //新增订单子表：订单每日优惠信息
            log.info("新增订单子表：订单每日优惠信息--start>>>");
            List<ReturnOrderEveryDayPromotions> everyDayPromotions = returnOrderInfo.getEveryDayPromotions();
            if(null != everyDayPromotions){
                List<SwitchOrderEveryDayPromotions> switchOrderEveryDayPromotionsList = new ArrayList<>();
                int soedpIntCount = 0;
                if (!everyDayPromotions.isEmpty() && everyDayPromotions.size() > 0) {
                    everyDayPromotions.forEach(orderEveryDayPromotions -> {
                                SwitchOrderEveryDayPromotions switchOrderEveryDayPromotions = new SwitchOrderEveryDayPromotions();
                                switchOrderEveryDayPromotions = (SwitchOrderEveryDayPromotions) Dto2Entity.populate(orderEveryDayPromotions, switchOrderEveryDayPromotions);

                                switchOrderEveryDayPromotions.setId(StringUtil.getUUID());
                                switchOrderEveryDayPromotions.setPId(swicthOrderInfoId);//父级SwitchOrderInfo id
                                switchOrderEveryDayPromotions.setState(state);
                                switchOrderEveryDayPromotions.setCreateTime(createTime);
                                switchOrderEveryDayPromotions.setModifyTime(modifyTime);

                                switchOrderEveryDayPromotionsList.add(switchOrderEveryDayPromotions);
                            }
                    );

                    soedpIntCount = switchOrderEveryDayPromotionsMapper.insertList(switchOrderEveryDayPromotionsList);
                }
                log.info("新增订单子表：订单每日优惠信息--end>>>成功执行{}条", soedpIntCount);
            }else{
                log.info("新增订单子表：订单每日优惠信息--null>>>成功执行0条");
            }



            //新增订单子表：订单扣款信息
            log.info("新增订单子表：订单扣款信息--start>>>");
            List<ReturnOrderLadderDeductPolice> ladderDeductPolicies = returnOrderInfo.getLadderDeductPolicies();
            if(null != ladderDeductPolicies){
                List<SwitchOrderLadderDeductPolice> switchOrderLadderDeductPoliceList = new ArrayList<>();
                int soldpIntCount = 0;
                if (!ladderDeductPolicies.isEmpty() && ladderDeductPolicies.size() > 0) {
                    ladderDeductPolicies.forEach(orderLadderDeductPolice -> {
                                SwitchOrderLadderDeductPolice switchOrderLadderDeductPolice = new SwitchOrderLadderDeductPolice();
                                switchOrderLadderDeductPolice = (SwitchOrderLadderDeductPolice) Dto2Entity.populate(orderLadderDeductPolice, switchOrderLadderDeductPolice);

                                switchOrderLadderDeductPolice.setId(StringUtil.getUUID());
                                switchOrderLadderDeductPolice.setPId(swicthOrderInfoId);//父级SwitchOrderInfo id
                                switchOrderLadderDeductPolice.setState(state);
                                switchOrderLadderDeductPolice.setCreateTime(createTime);
                                switchOrderLadderDeductPolice.setModifyTime(modifyTime);

                                switchOrderLadderDeductPoliceList.add(switchOrderLadderDeductPolice);
                            }
                    );

                    soldpIntCount = switchOrderLadderDeductPoliceMapper.insertList(switchOrderLadderDeductPoliceList);
                }
                log.info("新增订单子表：订单扣款信息--end>>>成功执行{}条", soldpIntCount);
            }else{
                log.info("新增订单子表：订单扣款信息--null>>>成功执行0条");
            }



        }

        return ret;
    }

    /**
     * 订单操作接口
     * 注：每分钟调用不得超过 10 次
     *
     * @param operateDltOrder
     * @return
     */
    @Override
    @Retryable(value = Exception.class, maxAttempts = 4, backoff = @Backoff(delay = 2000, multiplier = 1.5))
    public Result<Object> operaterDltOrder(OperateDltOrder operateDltOrder) {

        log.info("进入订单操作接口---->>>   : {}", operateDltOrder);
        //获取订单相关信息
        Map<String, Object> data = new HashMap<>();
        if (ObjectUtils.isEmpty(operateDltOrder.getOperaterType())) {
            return new Result<>(CommonEnums.FIELD_NULL);
        }

        /**
         *@Description: 1：按入住人姓名；2：按确认号  修改为按确认号
         *@Author: Zhang·jz
         *@date: 2020/8/17
         * start
         */
        //判断orderId 是否为空,根据订单id查询出对应的最新的代理通id
        if(!ObjectUtils.isEmpty(operateDltOrder) && !ObjectUtils.isEmpty(operateDltOrder.getOrderId())){
            SwitchOrderListNotify switchOrderListNotify = new SwitchOrderListNotify();
            //查找出状态为0的，进行操作
            switchOrderListNotify = switchOrderListNotifyMapper.findSwitchOrderListNotifyByOrderId(operateDltOrder.getOrderId());
            data.put("dltOrderId", switchOrderListNotify.getDltOrderId());
            //当操作类型 位 0（接受）时，录入确认号为订单号
//            if(!ObjectUtils.isEmpty(operateDltOrder.getConfirmType()) && operateDltOrder.getConfirmType() == 0){
//                data.put("confirmType", 2);  //调整为确认号
////                data.put("confirmType", operateDltOrder.getConfirmType());
//            }else{
//                data.put("confirmType", operateDltOrder.getConfirmType());
//            }
        }else{
            data.put("dltOrderId", operateDltOrder.getDltOrderId());
//            data.put("confirmType", operateDltOrder.getConfirmType());
        }
//        修改为按确认号
        data.put("confirmType", 2);
        /*end*/
        data.put("operaterType", operateDltOrder.getOperaterType());
        data.put("refuseType", operateDltOrder.getRefuseType());
        data.put("refuseRemark", operateDltOrder.getRefuseRemark());
        data.put("refundAmount", operateDltOrder.getRefundAmount());
        data.put("bookingNo", operateDltOrder.getBookingNo());
        data.put("remark", operateDltOrder.getRemark());

        String result = SwitchsHttpUtils.sendRequest(data, SwitchConstants.SWITCH_API_OPPERATER_DLT_ORDER, profile);
        //对结构进行格式化
//        JSONObject jsonObject = JSONObject.fromObject(result);
//        ResultStatusInfoVo resultStatusInfoVo = JSONUtils.toBean(jsonObject.getJSONObject("resultStatus"), ResultStatusInfoVo.class);

        Map<String,Object> map = JacksonUtil.parse(result,Map.class);
        ResultStatusInfoVo resultStatusInfoVo = JacksonUtil.parse(JacksonUtil.objectToJson(map.get("resultStatus")), ResultStatusInfoVo.class);
        //说明调用接口失败 <除了 0 是正确，别的都是错误>
        if (resultStatusInfoVo.getResultCode() != 0) {
            log.info("订单变化通知接口-调用接口失败 {}", resultStatusInfoVo);
            Result ret = new Result<>();
            ret.setData(resultStatusInfoVo.getResultCode());
            ret.setCode(CommonConstants.REQUEST_ERROR);
            ret.setMsg(resultStatusInfoVo.getResultMsg());
            return ret;
        } else {
            return new Result<>(resultStatusInfoVo.getResultMsg(), CommonConstants.SUCCESS);
        }
    }

    /**
     * 发单接口
     * 注：每分钟调用不得超过 10 次
     *
     * @param orderId
     * @return
     */
    @Override
    public Result<Object> issueOrder(String orderId) {
        log.info("----->进入发单方法：（issueOrder）");
        IssueOrderVo issueOrderVo = getIssueOrderVoByDltOrderId(orderId);
        if(ObjectUtils.isEmpty(issueOrderVo) || ObjectUtils.isEmpty(issueOrderVo.getOrderId()) || ObjectUtils.isEmpty(issueOrderVo.getSupplierID())){
            return new Result<>("发单对象-"+CommonEnums.DATA_NULL.getMsg(),CommonEnums.DATA_NULL.getCode());
        }
        //获取订单相关信息
        Map<String, Object> data = new HashMap<>();

        issueOrderVo.setSupplierID(SwitchConstants.SUPPLIERID_PROD);
        issueOrderVo.setRemarks(issueOrderVo.getRemarks() == null ? "无":issueOrderVo.getRemarks());
        // 将 实体类 转换为 Map
        data = JSON.parseObject(JSON.toJSONString(issueOrderVo), Map.class);
        Map<String, Object> reqData = new HashMap<>();
        reqData.put("issueOrder",data);
        log.info("发单 reqData result : {}",reqData);

        String result = SwitchsHttpUtils.sendRequest(reqData, SwitchConstants.SWITCH_API_ISSUE_ORDER, profile);
        log.info("发单 sendRequest result : {}",result);
        //对结构进行格式化
        Map<String,Object> map = JacksonUtil.parse(result,Map.class);
        ResultStatusInfoVo resultStatusInfoVo = JacksonUtil.parse(JacksonUtil.objectToJson(map.get("resultStatus")), ResultStatusInfoVo.class);

        //数据库操作返回状态不等-1 则操作成功
        int optInt = 0;
        //将发单数据加入表
        if(!ObjectUtils.isEmpty(issueOrderVo) && resultStatusInfoVo.getResultCode() == 0){
            String switchIssueOrderId = StringUtil.getUUID();
            int state = 0;//默认0
            Date createTime = new Date();
            Date modifyTime = new Date();

            if(!ObjectUtils.isEmpty(issueOrderVo.getDltOrderId())){
                log.info("发单主表信息；代理通订单号为："+issueOrderVo.getDltOrderId()+"数据；");
                SwitchIssueOrder switchIssueOrder = new SwitchIssueOrder();
                switchIssueOrder = (SwitchIssueOrder) Dto2Entity.populate(issueOrderVo, switchIssueOrder);
                switchIssueOrder.setId(switchIssueOrderId);
                switchIssueOrder.setCreateTime(createTime);
                switchIssueOrder.setModifyTime(modifyTime);
                switchIssueOrder.setState(state);
                switchIssueOrder.setRemark("订单变化通知接口-调用接口失败resultStatusInfoVo:{"+resultStatusInfoVo+"}" );

                optInt = switchIssueOrderMapper.insert(switchIssueOrder);
                //订单对应静态信息
                if(optInt != -1){
                    log.info("订单对应静态信息；staticInfo:{}",issueOrderVo.getStaticInfo());
                    SwitchIssueHotelAndRoomStatic switchIssueHotelAndRoomStatic = new SwitchIssueHotelAndRoomStatic();
                    switchIssueHotelAndRoomStatic = (SwitchIssueHotelAndRoomStatic) Dto2Entity.populate(issueOrderVo.getStaticInfo(), switchIssueHotelAndRoomStatic);
                    switchIssueHotelAndRoomStatic.setId(StringUtil.getUUID());
                    switchIssueHotelAndRoomStatic.setPId(switchIssueOrderId);//父级
                    switchIssueHotelAndRoomStatic.setCreateTime(createTime);
                    switchIssueHotelAndRoomStatic.setModifyTime(modifyTime);
                    switchIssueHotelAndRoomStatic.setState(state);

                    optInt = switchIssueHotelAndRoomStaticMapper.insert(switchIssueHotelAndRoomStatic);

                    //发单人信息
                    if(optInt != -1){
                        log.info("发单人信息；senderInfo:{}",issueOrderVo.getSenderInfo());
                        SwitchIssueSenderInfo switchIssueSenderInfo = new SwitchIssueSenderInfo();
                        switchIssueSenderInfo = (SwitchIssueSenderInfo) Dto2Entity.populate(issueOrderVo.getSenderInfo(), switchIssueSenderInfo);
                        switchIssueSenderInfo.setId(StringUtil.getUUID());
                        switchIssueSenderInfo.setPId(switchIssueOrderId);//父级
                        switchIssueSenderInfo.setCreateTime(createTime);
                        switchIssueSenderInfo.setModifyTime(modifyTime);
                        switchIssueSenderInfo.setState(state);

                        optInt = switchIssueSenderInfoMapper.insert(switchIssueSenderInfo);
                        //接单人信息
                        if(optInt != -1){
                            log.info("接单人信息；receiverInfo:{}",issueOrderVo.getReceiverInfo());
                            SwitchIssueReceiverInfo switchIssueReceiverInfo = new SwitchIssueReceiverInfo();
                            switchIssueReceiverInfo = (SwitchIssueReceiverInfo) Dto2Entity.populate(issueOrderVo.getReceiverInfo(), switchIssueReceiverInfo);
                            switchIssueReceiverInfo.setId(StringUtil.getUUID());
                            switchIssueReceiverInfo.setPId(switchIssueOrderId);//父级
                            switchIssueReceiverInfo.setCreateTime(createTime);
                            switchIssueReceiverInfo.setModifyTime(modifyTime);
                            switchIssueReceiverInfo.setState(state);

                            optInt = switchIssueReceiverInfoMapper.insert(switchIssueReceiverInfo);

                            //每日房价列表
                            if(optInt != -1){
                                List<ArrivalRoomVo> arrivalRoomVoList = new ArrayList<>();
                                List<SwitchIssueArrivalRoom> switchIssueArrivalRoomList = new ArrayList<>();
                                arrivalRoomVoList = issueOrderVo.getArrivalRoomList();
                                log.info("每日房价列表；arrivalRoomList:{}",arrivalRoomVoList);

                                if (!arrivalRoomVoList.isEmpty() && arrivalRoomVoList.size() > 0) {
                                    arrivalRoomVoList.forEach(arrivalRoomVo -> {
                                                SwitchIssueArrivalRoom switchIssueArrivalRoom = new SwitchIssueArrivalRoom();
                                                switchIssueArrivalRoom = (SwitchIssueArrivalRoom) Dto2Entity.populate(arrivalRoomVo, switchIssueArrivalRoom);

                                                switchIssueArrivalRoom.setId(StringUtil.getUUID());
                                                switchIssueArrivalRoom.setPId(switchIssueOrderId);//switchIssueOrderId id
                                                switchIssueArrivalRoom.setState(state);
                                                switchIssueArrivalRoom.setCreateTime(createTime);
                                                switchIssueArrivalRoom.setModifyTime(modifyTime);

                                                switchIssueArrivalRoomList.add(switchIssueArrivalRoom);
                                            }

                                    );

                                    if(!switchIssueArrivalRoomList.isEmpty() && switchIssueArrivalRoomList.size()>0){
                                        optInt = switchIssueArrivalRoomMapper.insertList(switchIssueArrivalRoomList);
                                    }

                                }

                            }
                        }


                    }
                }

            }

        }
        String optStr = "";
        if(optInt != -1){
            log.info("发单数据库新增成功！");
            optStr = " 发单数据库新增成功！";
        }else{
            optStr = " 发单数据库新增失败！";
        }

        //说明调用接口失败 <除了 0 是正确，别的都是错误>
        if (resultStatusInfoVo.getResultCode() != 0) {
            return new Result<>(resultStatusInfoVo.getResultMsg()+optStr, CommonConstants.REQUEST_ERROR);
        } else {
            return new Result<>(resultStatusInfoVo.getResultMsg()+optStr, CommonConstants.SUCCESS);
        }

    }

    /**
     * 根据代理通id 获取发单信息
     * @param orderId
     * @return
     */
    public IssueOrderVo getIssueOrderVoByDltOrderId(String orderId){
        IssueOrderVo issueOrderVo = new IssueOrderVo();

        //1：根据订单号查询基础发单信息：
        SwitchOrderInfo switchOrderInfo = new SwitchOrderInfo();
//        switchOrderInfo.setDltOrderId(dltOrderId);
//        switchOrderInfo.setDltOrderId(dltOrderId);
        Map switchOrderInfoMap = new HashMap();
        switchOrderInfoMap.put("orderId",orderId);
        switchOrderInfo = switchOrderInfoMapper.findOneByOrderId(switchOrderInfoMap);
        log.info("1. 根据订单号("+orderId+")获取订单信息-->switchOrderInfo: {}",switchOrderInfo);

        if(ObjectUtils.isEmpty(switchOrderInfo)){
            return new IssueOrderVo();
        }

        issueOrderVo.setDltOrderId(switchOrderInfo.getDltOrderId());
        issueOrderVo.setOrderId(switchOrderInfo.getOrderId());
        issueOrderVo.setOrderType(switchOrderInfo.getFormType());//N-新订，M-修改，C-取消，D-延住
        issueOrderVo.setRoomPaymentType(0);//房费付款方式 0-我司预付，1-我司挂账
        issueOrderVo.setExPaymentType(1);//杂费付款方式 0-客人自理，1-我司预付，2-我司挂账
        issueOrderVo.setClientName(switchOrderInfo.getCustomerName());
        issueOrderVo.setContactInformation("4009700950");//客人联系方式.默认公司人员电话
        issueOrderVo.setRemarks(switchOrderInfo.getOrderMemo());//订单备注
        issueOrderVo.setBookDescription("无");//预定说明
        issueOrderVo.setIssueType("3");//发单类型 0-Ebk，1-传真，2-Email,5-PMS 3:qq/微信
//        issueOrderVo.setFaxFormatNo(1);//传真发单模板号 1，2，3，4，5，9
//        issueOrderVo.setReceiverFaxOrEmail();//收件人邮箱或者Fax 发单方式为1或2是必传
//        issueOrderVo.setBIDCode();//发单人BID号码 issueType=5&& faxFormatNo=5时必传
        issueOrderVo.setCheckinDate(switchOrderInfo.getCheckinDate());
        issueOrderVo.setCheckoutDate(switchOrderInfo.getCheckoutDate());
        issueOrderVo.setCurrency(switchOrderInfo.getOrderCurrency());
        issueOrderVo.setSendAmount(switchOrderInfo.getAfterDiscountPrice() == null ? "0" :switchOrderInfo.getAfterDiscountPrice().toString());//发单总金额
        issueOrderVo.setQuantity(switchOrderInfo.getRoomnum());
        issueOrderVo.setIsHideRoomAmount("T");//是否隐藏房费  F-否，T-是，C-采购编码发单

        log.info("1-1. 根据订单号("+orderId+")获取订单信息-->issueOrderVo: {}",issueOrderVo);
        //2.订单对应静态信息
        HotelAndRoomStaticVo hotelAndRoomStaticVo = new HotelAndRoomStaticVo();
        hotelAndRoomStaticVo.setHotelId(switchOrderInfo.getHotelId());
        hotelAndRoomStaticVo.setHotelName(switchOrderInfo.getHotelName());
        hotelAndRoomStaticVo.setHotelEName(switchOrderInfo.getHotelEName());
        hotelAndRoomStaticVo.setRoomId(switchOrderInfo.getRoomId());
        hotelAndRoomStaticVo.setRoomName(switchOrderInfo.getRoomName());
        hotelAndRoomStaticVo.setBasicRoomName(switchOrderInfo.getRoomName());

        issueOrderVo.setStaticInfo(hotelAndRoomStaticVo);//设置静态信息

        log.info("2. 订单对应静态信息-->hotelAndRoomStaticVo:{}",hotelAndRoomStaticVo);

        //3.发单人信息 - 待确认
        ContactsVo contactsVoSend = new ContactsVo();
        contactsVoSend.setName("很好住");//发单方名称
//        contactsVoSend.setFax();//发单方传真号
//        contactsVoSend.setEmail();//发单方邮箱
        contactsVoSend.setContacts("4009700950");//发单方联系方式

        issueOrderVo.setSenderInfo(contactsVoSend);

        log.info("3. 发单人信息-->contactsVoSend:{}",contactsVoSend);

        //根据母酒店HotelId 获取酒店联系人信息以及电话
        SwitchMasterHotelInfo switchMasterHotelInfo = new SwitchMasterHotelInfo();

        Example example = new Example(SwitchMasterHotelInfo.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("hotelName",switchOrderInfo.getHotelName());
        example.setOrderByClause(" id limit 1");

        switchMasterHotelInfo = switchMasterHotelInfoMapper.selectOneByExample(example);

        log.info("3-1. 发单人信息-->switchMasterHotelInfo:{}",switchMasterHotelInfo);
        if(ObjectUtils.isEmpty(switchMasterHotelInfo)){
            return new IssueOrderVo();
        }
        //4.接单人信息
        ContactsVo contactsVoReceive = new ContactsVo();
        contactsVoReceive.setName(switchMasterHotelInfo.getHotelName());//接单方名称
//        contactsVoReceive.setFax();//接单方传真号
//        contactsVoReceive.setEmail();//接单方邮箱
        contactsVoReceive.setContacts(switchMasterHotelInfo.getHotelPhone());//接单方联系方式

        issueOrderVo.setReceiverInfo(contactsVoReceive);

        log.info("4. 接单人信息-->contactsVoReceive:{}",contactsVoReceive);

        //获取对应订单每日房价
        List<SwitchOrderRoomPrice> switchOrderRoomPriceList = new ArrayList<>();
        SwitchOrderRoomPrice switchOrderRoomPrice = new SwitchOrderRoomPrice();

        Example examplePrice = new Example(SwitchOrderRoomPrice.class);
        Example.Criteria criteriaPrice = examplePrice.createCriteria();
        criteriaPrice.andEqualTo("pId",switchOrderInfo.getId());//根据订单uuid，获取对应每日房价列表
        switchOrderRoomPriceList = switchOrderRoomPriceMapper.selectByExample(examplePrice);

        if(switchOrderRoomPriceList.isEmpty() || switchOrderRoomPriceList.size() ==0){
            return new IssueOrderVo();
        }
        log.info(" 获取对应订单每日房价-->switchOrderRoomPriceList:{}",switchOrderRoomPriceList);
        //5.设置发单每日房价
        List<ArrivalRoomVo> arrivalRoomVoList = new ArrayList<>();
        arrivalRoomVoList = (List<ArrivalRoomVo>) Dto2Entity.populateList(switchOrderRoomPriceList,arrivalRoomVoList, ArrivalRoomVo.class);

        issueOrderVo.setArrivalRoomList(arrivalRoomVoList);

        if(arrivalRoomVoList.isEmpty() || arrivalRoomVoList.size() ==0){
            return new IssueOrderVo();
        }
        log.info("5. 设置发单每日房价-->arrivalRoomVoList:{}",arrivalRoomVoList);
        log.info("6. 发单信息-->issueOrderVo:{}",issueOrderVo);
        return issueOrderVo;
    }

    /**
     * 订单列表查询接口
     * 注：每分钟调用不得超过 10 次
     *
     * @param requestCheckOrderVo
     * @return
     */
    @Override
    @Retryable(value = Exception.class, maxAttempts = 4, backoff = @Backoff(delay = 2000, multiplier = 1.5))
    public Result<List<ReturnDltOrderInfoCheckVo>> getDltOrderList(RequestCheckOrderVo requestCheckOrderVo) {
        //获取订单相关信息
        Map<String, Object> data = new HashMap<>();
        data.put("orderId", requestCheckOrderVo.getOrderId());
        Map pagingType = new HashMap();
        pagingType.put("pageSize", requestCheckOrderVo.getPageSize());
        pagingType.put("pageIndex", requestCheckOrderVo.getPageIndex());
        data.put("pagingType", pagingType);

        String result = SwitchsHttpUtils.sendRequest(data, SwitchConstants.SWITCH_API_GET_DLT_ORDER_LIST, profile);
        //对结构进行格式化
//        JSONObject jsonObject = JSONObject.fromObject(result);
//        ResultStatusInfoVo resultStatusInfoVo = JSONUtils.toBean(jsonObject.getJSONObject("resultStatus"), ResultStatusInfoVo.class);

        Map<String,Object> map = JacksonUtil.parse(result,Map.class);
        ResultStatusInfoVo resultStatusInfoVo = JacksonUtil.parse(JacksonUtil.objectToJson(map.get("resultStatus")), ResultStatusInfoVo.class);
        //说明调用接口失败 <除了 0 是正确，别的都是错误>
        if (resultStatusInfoVo.getResultCode() != 0) {
            log.info("订单变化通知接口-调用接口失败{}", resultStatusInfoVo);
            return new Result<>(resultStatusInfoVo.getResultMsg(), CommonConstants.REQUEST_ERROR);
        }

        //解析返回值，并转为对应vo输出
//        List<ReturnDltOrderInfoCheckVo> returnDltOrderInfoCheckVoList = JSONUtils.toList(jsonObject.getJSONObject("dltOrderList"), ReturnDltOrderInfoCheckVo.class);
        List<ReturnDltOrderInfoCheckVo> returnDltOrderInfoCheckVoList = JacksonUtil.jsonToList(JacksonUtil.objectToJson(map.get("dltOrderList")), ReturnDltOrderInfoCheckVo.class);
                //读取相关订单数据库
        log.info("返回查询订单{}", returnDltOrderInfoCheckVoList);
        return new Result<>(returnDltOrderInfoCheckVoList);
    }

/****************************************************操作订单流程 starting*******************************************************************/

    /**
     * 操作携程和美团订单
     *      * @param md5Key
     */
    @Override
    public Result<Object> operateSwitchAndMeituanOrderByOrderId(String md5Key){
        log.info("操作携程和美团订单11--operateSwitchAndMeituanOrderByOrderId-->");
        //如果订单是否为空，是则不操作
        if(ObjectUtils.isEmpty(md5Key)) {
            return new Result<>(CommonEnums.DATA_NULL);
        }
        Example example = new Example(SwitchOrderListNotify.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("md5Key",md5Key);
        SwitchOrderListNotify switchOrderListNotify = switchOrderListNotifyMapper.selectOneByExample(example);
        if(ObjectUtils.isEmpty(switchOrderListNotify)){
            return new Result<>(CommonConstants.ERROR);
        }
        String dltOrderId = switchOrderListNotify.getDltOrderId();//代理同订单id
        Result<Object> ret = new Result<>();
        //不为空继续操作
        //1：先根据订单号，获取订单详细信息，并做订单详情数据新增；为了获取到对应酒店id 和房型id
        SwitchOrderInfo switchOrderInfo = new SwitchOrderInfo();
//        switchOrderInfo.setDltOrderId(dltOrderId);
//        switchOrderInfo = switchOrderInfoMapper.selectOne(switchOrderInfo);

        String orderId = switchOrderListNotify.getOrderId();//订单id
        Map switchOrderInfoMap = new HashMap();
        switchOrderInfoMap.put("orderId",orderId);
        switchOrderInfo = switchOrderInfoMapper.findOneByOrderId(switchOrderInfoMap);
        log.info("operateSwitchAndMeituanOrderByOrderId --->1. 根据订单号("+orderId+")获取订单信息-->switchOrderInfo: {}",switchOrderInfo);


        Result<Object> orderDetailResult= new Result<>();

        //判断订单详情是否已经拉取
        if(ObjectUtils.isEmpty(switchOrderInfo)){
            orderDetailResult = getdltorderinfo(dltOrderId);
            if(ObjectUtils.isEmpty(orderDetailResult) || orderDetailResult.getCode()!=CommonConstants.SUCCESS){
                log.info("读取订单号为：（"+dltOrderId+"）；详情数据失败；orderDetailResult:{}",orderDetailResult);
                return new Result<>((String)orderDetailResult.getMsg(),CommonConstants.ERROR);
            }
        }else{
            //酒店相关信息赋值
            hotelId = switchOrderInfo.getHotelId();
            roomId = switchOrderInfo.getRoomId();
            time = DateUtil.switchDateParse(switchOrderInfo.getCheckinDate() == null ? null:switchOrderInfo.getCheckinDate().toString());
            price = switchOrderInfo.getOrderPrice()== null ? null:switchOrderInfo.getOrderPrice().doubleValue();
            endTime = DateUtil.switchDateParse(switchOrderInfo.getCheckoutDate().toString());
            num = switchOrderInfo.getRoomnum();

            formType = switchOrderListNotify.getFormType();//订单类型
        }

        log.info("hotelId:{"+hotelId+"}-roomId:{"+roomId+"}-time:{"+time+"}-endTime:{"+endTime+"}-price:{"+price+"}-num:{"+num+"}-formType:{"+formType+"}");
        if(ObjectUtils.isEmpty(hotelId.trim()) || ObjectUtils.isEmpty(roomId.trim()) || ObjectUtils.isEmpty(time.trim())
                || (ObjectUtils.isEmpty(price) || Double.compare(price,0) <= 0) || ObjectUtils.isEmpty(formType.trim())){
            return new Result<>(CommonEnums.DATA_NULL);
        }

        log.info("操作携程和美团订单--formType-->{}",formType);
        formType = formType.toUpperCase();//转大写
        Result thisResult = new Result();
        //获取订单状态 默认 N N-新订    * M-修改     * C-取消     * D-延住
        if("N".equals(formType)){
            //2020-09-14 调整优化订单流程
            thisResult = insertNewOperateSwitchAndMeituanOrderNew(switchOrderListNotify,dltOrderId,orderDetailResult);
        }else if("D".equals(formType)){
            //2020-09-14 调整优化订单流程
            thisResult = insertNewOperateSwitchAndMeituanOrderNew(switchOrderListNotify,dltOrderId,orderDetailResult);
        }else if("C".equals(formType)){
            Result thisResultC = cancelNewOperateSwitchAndMeituanOrderNew(switchOrderListNotify,dltOrderId);//2020-09-14 调整优化订单流程
            log.info("operateSwitchAndMeituanOrderByOrderId --thisResultC -->> {}",JacksonUtil.objectToJson(thisResultC));
            int retCode = thisResultC.getCode();
            //操作携程订单接口相关类
            OperateDltOrder operateDltOrder = new OperateDltOrder();
            operateDltOrder.setOrderId(orderId);
            //调用携程操作订单接口返回值
            Result operateRet = new Result();

            //如果是延时单每次调用美团下单则存储美团下单返回值至isDealRemark
            Map isDealMap = new HashMap();
            String isDealRemark = DateUtil.getNowTime() + " ";
            isDealMap.put("id",switchOrderListNotify.getId());
            isDealMap.put("isDeal",1);
            //美团接口返回用户已入住！ 直接决绝取消
            if(retCode == CommonEnums.MEITUAN_ORDER_CHECK_STATE_IN.getCode()){
                operateDltOrder.setOperaterType(12);//拒绝取消
                operateDltOrder.setRefuseType(3);//3:其他原因
                operateDltOrder.setRefuseRemark("用户已入住");
                operateDltOrder.setConfirmType(2);//确认方式： 2 - 确认号
                operateRet = operaterDltOrder(operateDltOrder);
                if(!ObjectUtils.isEmpty(operateRet) && operateRet.getCode() == CommonConstants.SUCCESS){
                    isDealRemark = isDealRemark + "当前订单用户已入住，不可取消！操作携程接口成功！携程操作订单接口返回：【"+JacksonUtil.objectToJson(operateRet)+"】";
                }else{
                    isDealRemark = isDealRemark + "当前订单用户已入住，不可取消！操作携程接口失败！携程操作订单接口返回：【"+JacksonUtil.objectToJson(operateRet)+"】";
                }
                SendUtils.dingMsgOrder("用户取消不受理",DateUtil.getNowTime()+" 美团酒店已入住不可取消 订单号："+orderId,MessageEnums.genre.REFUDE_ERROR.getCode(),orderId,restTemplate);
            }else if(retCode == CommonEnums.MEITUAN_ORDER_DATA_NULL.getCode()){//美团酒店未下单！ 直接接受取消
                operateDltOrder.setOperaterType(11);//11-接受取消,
                operateRet = operaterDltOrder(operateDltOrder);
                if(!ObjectUtils.isEmpty(operateRet) && operateRet.getCode() == CommonConstants.SUCCESS){
                    isDealRemark = isDealRemark + "当前订单美团酒店未下单, 直接接受取消！操作携程接口成功！携程操作订单接口返回：【"+JacksonUtil.objectToJson(operateRet)+"】";
                }else{
                    isDealRemark = isDealRemark + "当前订单美团酒店未下单, 直接接受取消！操作携程接口失败！携程操作订单接口返回：【"+JacksonUtil.objectToJson(operateRet)+"】";
                }
            }else {
                isDealRemark = isDealRemark + "已调用美团取消接口！";
            }

            isDealMap.put("isDealRemark",isDealRemark);
            log.info("operateSwitchAndMeituanOrderByOrderId --- isDealMap ： {}",isDealMap);
            int updInt = switchOrderListNotifyMapper.updateNotifyOrderIsDealById(isDealMap);
            if(updInt != -1){
                log.info("operateSwitchAndMeituanOrderByOrderId --- >> 取消单 携程通知单表修改成功！");
            }

            log.info("operateSwitchAndMeituanOrderByOrderId =====调用携程操作订单接口返回值 -- operateRet -->> {}",operateRet);
            return thisResultC;
        }

        SwitchOrderPool switchOrderPool = new SwitchOrderPool();
        if(!ObjectUtils.isEmpty(thisResult.getData())){
            switchOrderPool = (SwitchOrderPool) thisResult.getData();
        }

        //直接操作新增到订单池2020-09-14
        int retCode = thisResult.getCode();
        //订单新增入订单池,如果是立即下单
        if(retCode == CommonConstants.SUCCESS && switchOrderPool.getIsOrder() ==1){
            //订单池操作成功,调用操作美团下单接口
            //新增订单会先查询订单详情并新增到库表，此地需要重新查询一次
            orderId = switchOrderPool.getOrderId();//订单id
            Map switchOrderInfoNewMap = new HashMap();
            switchOrderInfoNewMap.put("orderId",orderId);
            switchOrderInfo = switchOrderInfoMapper.findOneByOrderId(switchOrderInfoNewMap);
            log.info("getdltordernotify --switchOrderInfo--->{}",switchOrderInfo);
            //请求参数
            MtHotelOrderJobDealVo mtHotelOrderJobDealVo = new MtHotelOrderJobDealVo();
            mtHotelOrderJobDealVo.setSwPoolId(switchOrderPool.getId());
            mtHotelOrderJobDealVo.setSwOrderId(orderId);
            mtHotelOrderJobDealVo.setSwHotelId(switchOrderInfo.getHotelId());
            mtHotelOrderJobDealVo.setSwRoomId(switchOrderInfo.getRoomId());
            mtHotelOrderJobDealVo.setCheckinDate(DateUtil.switchDateParse(switchOrderInfo.getCheckinDate()));
            mtHotelOrderJobDealVo.setCheckoutDate(DateUtil.switchDateParse(switchOrderInfo.getCheckoutDate()));
            mtHotelOrderJobDealVo.setRoomnum(switchOrderInfo.getRoomnum());
            mtHotelOrderJobDealVo.setTotalPrice(switchOrderInfo.getOrderPrice().multiply(new BigDecimal(100)).intValue());
            mtHotelOrderJobDealVo.setPersonNames(switchOrderInfo.getCustomerName());
            mtHotelOrderJobDealVo.setContactName(switchOrderInfo.getContactName());
            mtHotelOrderJobDealVo.setContactPhone("4009700950");
            //获取美团对应酒店id 商品id
            SwitchCreateRoomDto switchCreateRoomDto = switchCreateRoomService.getMtInfoBySwitchRoomId(Integer.valueOf(roomId));
            log.info("getdltordernotify --switchCreateRoomDto--->{}",switchCreateRoomDto);
            mtHotelOrderJobDealVo.setMtHotelId(String.valueOf(switchCreateRoomDto.getMtHotelId()));
            mtHotelOrderJobDealVo.setGoodsId(switchCreateRoomDto.getMtGoodId());
            String dataJson = JacksonUtil.objectToJson(mtHotelOrderJobDealVo);
            log.info("getdltordernotify --开始调用美团下单接口---dataJson--->{}",dataJson);
            //调用美团下单接口
            thisResult = RestTemplateUtils.post(CommonUrlConstants.MEITUAN_HOST+"/mtHotelOrderDeal/jobNewOrderBooking",dataJson,restTemplate);
//            thisResult.setCode(CommonConstants.SUCCESS);
            int getMTBookCount = 0;
            log.info("getdltordernotify 调用美团下单接口 thisResult ： {}",thisResult);
            //如果返回成功，修改通知单isDeal 为 1
            while (getMTBookCount <= 3 && (ObjectUtils.isEmpty(thisResult) || (thisResult.getCode() != CommonConstants.SUCCESS))){
                getMTBookCount++;
                thisResult = RestTemplateUtils.post(CommonUrlConstants.MEITUAN_HOST+"/mtHotelOrderDeal/jobNewOrderBooking",dataJson,restTemplate);
            }

            //如果是延时单每次调用美团下单则存储美团下单返回值至isDealRemark
            Map isDealMap = new HashMap();
            String isDealRemark = DateUtil.getNowTime()+" 美团下单；美团返回："+String.valueOf(thisResult);
            isDealMap.put("id",switchOrderListNotify.getId());
            isDealMap.put("isDeal",1);
            isDealMap.put("isDealRemark",isDealRemark);

            log.info("getdltordernotify --- isDealMap ： {}",isDealMap);
            int updInt = switchOrderListNotifyMapper.updateNotifyOrderIsDealById(isDealMap);
            if(updInt != -1){
                log.info("getdltordernotify --- >> 携程通知单表修改成功！");
            }

        }


        return thisResult;
    }

    @Override
    public SwitchOrderInfo getDltOrderInfoByDltId(String orderId) {
        Map map = new HashMap();
        map.put("orderId",orderId);
        SwitchOrderInfo one = switchOrderInfoMapper.findOneByOrderId(map);
        return one;
    }

    /**
     * 用途：处理通知单 调用  checkBookingOrderResult
     * @param switchOrderInfoDto
     * @param mtHotelOrderCheckVo
     * @return
     */
    public Result<Object> checkBookingOrderResult(SwitchOrderInfoDto switchOrderInfoDto, MtHotelOrderCheckVo mtHotelOrderCheckVo) {
        log.info("进入--->>checkBookingOrderResult -switchOrderInfoDto--> {}  -mtHotelOrderCheckVo-- {}",JacksonUtil.objectToJson(switchOrderInfoDto),JacksonUtil.objectToJson(mtHotelOrderCheckVo));
        if(null == switchOrderInfoDto){
            return new Result<>(CommonConstants.REQUEST_ERROR);
        }
        if(null == switchOrderInfoDto.getGoodsId()){
            return new Result<>("switchOrderInfoDto goodsId null", CommonConstants.REQUEST_ERROR);
        }
        if(null == switchOrderInfoDto.getCheckinDate()){
            return new Result<>("switchOrderInfoDto checkinDate null", CommonConstants.REQUEST_ERROR);
        }
        if(null == switchOrderInfoDto.getCheckoutDate()){
            return new Result<>("switchOrderInfoDto checkoutDate null", CommonConstants.REQUEST_ERROR);
        }
        if(null == switchOrderInfoDto.getRoomId()){
            return new Result<>("switchOrderInfoDto roomId null", CommonConstants.REQUEST_ERROR);
        }
        if(null == switchOrderInfoDto.getHotelId()){
            return new Result<>("switchOrderInfoDto hotelId null", CommonConstants.REQUEST_ERROR);
        }
        if(null == switchOrderInfoDto){
            return new Result<>(CommonConstants.REQUEST_ERROR);
        }
        return checkCode(switchOrderInfoDto,mtHotelOrderCheckVo);
    }

    public Result checkCode(SwitchOrderInfoDto switchOrderInfoDto,MtHotelOrderCheckVo mtHotelOrderCheckVo){
        log.info("美团下单前校验vo 调用公共checkCode方法，校验vo结果   开始时间：{},switchOrderInfoDto={},mtHotelOrderCheckVo={}",DateUtil.getCurrTime(), JSON.toJSONString(switchOrderInfoDto), JSON.toJSONString(mtHotelOrderCheckVo));


        Result result = new Result();
        result.setCode(-1);
        result.setMsg("异常未处理");

        Integer checkCode = mtHotelOrderCheckVo.getCode();//美团校验返回结果code
        Integer checkVoRemainRoomNum = mtHotelOrderCheckVo.getRemainRoomNum();//校验美团返回库存
        String switchsHotelId = switchOrderInfoDto.getHotelId();//携程酒店id
        Integer goodsId = switchOrderInfoDto.getGoodsId();//美团产品id
        String roomId = switchOrderInfoDto.getRoomId();//携程售卖房型id
        Integer roomnum = switchOrderInfoDto.getRoomnum();//携程订单房间数量
        String checkinDate = switchOrderInfoDto.getCheckinDate();//入住时间
        String checkoutDate = switchOrderInfoDto.getCheckoutDate();//离店时间
        Integer switchsTotalPrice = switchOrderInfoDto.getTotalPrice()*100;//携程价格 元--> 分

        if(checkCode==0){//接口返回code=0是校验通过，不代表价格没变化，要比较价格
            log.info(" 下单前校验得到返回，进入公共判断校验数据方法 updateSwitchsOrderByMtBookingBeforeCode，当前数据为code=0");
            //再次比对价格是否正确
            List<MtHotelOrderCheckPricesVo> priceModels = mtHotelOrderCheckVo.getPriceModels();
            Integer thisPrice = 0;
            for (MtHotelOrderCheckPricesVo p:priceModels){
                thisPrice += p.getSalePrice();
            }

            checkCode = 8;// version  qyy  20200908  系统逻辑里美团价格不会等于携程订单价格 ，每次都要携程接口再校验是否价格合理，code=0也可能存在价格变化
            Integer newMtTotal = roomnum*thisPrice;
            log.info(" checkCode = 0 再次校验价格code改为8 switchOrderInfoDto={} ，switchsTotalPrice={} ，newMtTotal={}", JSON.toJSONString(switchOrderInfoDto),switchsTotalPrice,newMtTotal);
            /*Integer newMtTotal = roomnum*thisPrice;//美团最新价格 单位分
            if(BigDecimal.valueOf(switchsTotalPrice).compareTo(BigDecimal.valueOf(newMtTotal)) != 0){
                checkCode = 8;//价格发送变化
                log.info(" checkCode  当前数据为code=0但实际价格发送了改变,修改code=8，{}，switchsTotalPrice!=newTotal {} {}",JSON.toJSONString(switchOrderInfoDto),switchsTotalPrice,newMtTotal);
            }*/
        }
        if(0 == checkCode || 8 == checkCode){
            //校验成功 0   ， 价格发送变化 8
            if(0 == checkCode){
                result = new Result<>("该checkCode = 0,校验成功,当前接口返回成功",CommonConstants.SUCCESS);//0：校验成功
            }else if(8 == checkCode){
                int newMtTotalPrice = mtHotelOrderCheckVo.getPriceModels().stream().mapToInt(MtHotelOrderCheckPricesVo::getSalePrice).sum() * roomnum;//重新计算总价:美团返回的单价相加
                Integer state = switchIsCanAccept(goodsId,checkinDate,checkoutDate,
                        switchsTotalPrice,newMtTotalPrice);//价格发送改变，重新请求携程接口校验是否可以接单  //0 价格变高(拒绝订单)  1 价格变低(接受订单) 2 (获取美团的日历数据获取到空)  稍后重试 3 加了6%还是低于美团价格
                if (null == state) {
                    result = new Result<>("checkCode = 8,携程接口校验是否可以接单接口异常返回null，当前接口返回失败",CommonConstants.ERROR);
                }else{
                    if (state == 0) {
                        result = new Result<>("美团价格变高",CommonConstants.ERROR);//当前接口返回失败
                    }else if (state == 3) {
                        result = new Result<>("加了6%还是低于美团价格",CommonConstants.ERROR);//当前接口返回失败
                    }else if (state == 1) {
                        result = new Result<>("checkCode = 8,判断为价格变低，接受订单，当前接口返回成功",CommonConstants.SUCCESS);
                    }else{
                        result = new Result<>("checkCode = 8,携程接口校验是否可以接单 2 (获取美团的日历数据获取到空)",CommonConstants.ERROR);//,当前接口返回失败
                    }
                }
            }
            // 0 或 8 更新携程修改库存
            switchModifyRemain(switchsHotelId,roomId,checkinDate,checkoutDate,checkVoRemainRoomNum);
        }else{
            //校验未通过，拒绝订单
            result = new Result<>("下单前校验校验未通，美团接口返回 = "+ JSON.toJSONString(mtHotelOrderCheckVo),CommonConstants.ERROR);
        }
        log.info("美团下单前校验vo 调用公共checkCode方法，校验vo结果   结束时间：{},result={}",DateUtil.getCurrTime(), JSON.toJSONString(result));
        return result;
    }

    /**
     * 下单定时器调用：修改携程订单相关根据美团下单前校验code
     * @param switchOrderInfoDto
     * @param mtHotelOrderCheckVo
     * @return
     */
    @Override
    public Result<Object> updateSwitchsOrderByMtBookingBeforeCode(SwitchOrderInfoDto switchOrderInfoDto,MtHotelOrderCheckVo mtHotelOrderCheckVo) {
        log.info("下单定时器调用：校验checkCode  进入方法updateSwitchsOrderByMtBookingBeforeCode  开始时间 {}，switchOrderInfoDto={}，mtHotelOrderCheckVo={}",DateUtil.getCurrTime(), JSON.toJSONString(switchOrderInfoDto), JSON.toJSONString(mtHotelOrderCheckVo));
        if(null == switchOrderInfoDto){
            return new Result<>(CommonConstants.REQUEST_ERROR);
        }
        if(null == switchOrderInfoDto.getGoodsId()){
            return new Result<>("switchOrderInfoDto goodsId null", CommonConstants.REQUEST_ERROR);
        }
        if(null == switchOrderInfoDto.getCheckinDate()){
            return new Result<>("switchOrderInfoDto checkinDate null", CommonConstants.REQUEST_ERROR);
        }
        if(null == switchOrderInfoDto.getCheckoutDate()){
            return new Result<>("switchOrderInfoDto checkoutDate null", CommonConstants.REQUEST_ERROR);
        }
        if(null == switchOrderInfoDto.getOrderPoolId()){
            return new Result<>("switchOrderInfoDto orderPoolId null", CommonConstants.REQUEST_ERROR);
        }
        if(null == switchOrderInfoDto.getSysOrderState()){
            return new Result<>("switchOrderInfoDto getSysOrderState null", CommonConstants.REQUEST_ERROR);
        }
        if(null == switchOrderInfoDto.getRoomId()){
            return new Result<>("switchOrderInfoDto roomId null", CommonConstants.REQUEST_ERROR);
        }
        if(null == switchOrderInfoDto.getHotelId()){
            return new Result<>("switchOrderInfoDto hotelId null", CommonConstants.REQUEST_ERROR);
        }
        if(null == switchOrderInfoDto){
            return new Result<>(CommonConstants.REQUEST_ERROR);
        }

        Result result = checkCode(switchOrderInfoDto,mtHotelOrderCheckVo);
        if(result.getCode()!= CommonConstants.SUCCESS){
            log.info("下单定时器调用：校验checkCode   返回失败：{}", JSON.toJSONString(result));
            if(result.getMsg().toString().contains("价格变高") || result.getMsg().toString().contains("校验未通过") || result.getMsg().toString().contains("加了6%")){
                switchOrderInfoDto.setSysOrderState(2);//待拒绝
                switchOrderInfoDto.setIsOrder(0);//延迟单
                switchOrderInfoDto.setOrderWaitTime(CommonConstants.SWITCH_ORDER_WAIT_TIME);//120分钟
                switchOrderInfoDto.setIsOrderRemark(DateUtil.getCurrTime()+" 下单定时器 下单前校验公共check失败 改为延时单");
                updateOrderResult(mtHotelOrderCheckVo, switchOrderInfoDto,DateUtil.getCurrTime()+" 下单定时器 下单前校验公共check失败 改为延时单"+"："+result.getMsg().toString());
                log.info("下单定时器调用：校验checkCode  进入方法updateSwitchsOrderByMtBookingBeforeCode  结束时间 {}，result={}",DateUtil.getCurrTime(), JSON.toJSONString(result));
                return new Result<>(result.getMsg(),CommonConstants.DELAY_ERROR);
            }
        }
        log.info("下单定时器调用：校验checkCode  进入方法updateSwitchsOrderByMtBookingBeforeCode  结束时间 {}，result={}",DateUtil.getCurrTime(), JSON.toJSONString(result));
        return result;
    }



    private Integer switchIsCanAccept(Integer mtGoodsId,String checkinDate,String checkoutDate,Integer switchsTotalPrice,Integer newMtTotalPrice) {
        Integer state = null;
        CanAcceptVo canAcceptVo = new CanAcceptVo();
        canAcceptVo.setMtGoodId(mtGoodsId);
        canAcceptVo.setStartTime(DateUtil.switchDateParse(checkinDate));
        canAcceptVo.setEndTime(DateUtil.switchDateParse(checkoutDate));
        canAcceptVo.setSwPrice(switchsTotalPrice);//分
        canAcceptVo.setMtPrice(newMtTotalPrice);//分
        log.info("////////////  公共方法 校验 美团checkcdoe，code==8,进入方法 switchIsCanAccept，参数：{},{}", JSON.toJSONString(canAcceptVo), JSON.toJSONString(canAcceptVo));
        Result response = switchPushRoomService.isCanAccept(canAcceptVo);
        log.info("////////////  公共方法 校验 美团checkcdoe，code==8,进入方法 switchIsCanAccept，返回：{}",response);
        if (null != response) {//0 价格变高(拒绝订单)  1 价格变低(接受订单) 2 (获取美团的日历数据获取到空)  稍后重试 3 加了6%还是低于美团价格
            Object data = response.getData();
            state = JacksonUtil.objToBean(data, Integer.class);
        }
        return state;
    }
    /**
     * <H1>更新携程订单实时状态池</H1>
     *
     * @param mtHotelOrderCheckVo
     * @param switchOrderInfoDto
     * @author HuangT
     * @date 2020/7/9 16:55
     */
    private void updateOrderResult(MtHotelOrderCheckVo mtHotelOrderCheckVo, SwitchOrderInfoDto switchOrderInfoDto,String remark) {
        log.info("updateOrderResult 更新携程订单实时状态池  {}", JSON.toJSONString(mtHotelOrderCheckVo), JSON.toJSONString(switchOrderInfoDto));
        //请求参数
        Map<String, Object> dataMap = new HashMap<>();
        //设置sysOrderState状态为拒绝(校验不通过)
        SwitchOrderPool switchOrderPool = new SwitchOrderPool();
        switchOrderPool.setId(switchOrderInfoDto.getOrderPoolId());
        switchOrderPool.setOrderId(switchOrderInfoDto.getOrderId());
        switchOrderPool.setMtDistributorOrderId(switchOrderInfoDto.getDistributorOrderId());
        switchOrderPool.setMeituanOrderId(switchOrderInfoDto.getMeituanOrderId());
        switchOrderPool.setIsOrder(switchOrderInfoDto.getIsOrder());
        switchOrderPool.setOrderWaitTime(switchOrderInfoDto.getOrderWaitTime());
        switchOrderPool.setIsOrderRemark(switchOrderInfoDto.getIsOrderRemark());
        switchOrderPool.setSysOrderState(switchOrderInfoDto.getSysOrderState());
        switchOrderPool.setMtCode(String.valueOf(mtHotelOrderCheckVo.getCode()));
        switchOrderPool.setMtDesc(mtHotelOrderCheckVo.getDesc());
        switchOrderPool.setMtPriceModels(JacksonUtil.objectToJson(mtHotelOrderCheckVo.getPriceModels()));
        switchOrderPool.setMtRemainRoomNum(String.valueOf(mtHotelOrderCheckVo.getRemainRoomNum()));
        switchOrderPoolService.updateOrderResult(switchOrderPool);

        this.insertPoolStateHistroy(switchOrderPool.getOrderId(),switchOrderPool.getSysOrderState(),
                switchOrderPool.getMtOrderState(),switchOrderPool.getIsOrder(),DateUtil.getCurrTime()+" "+remark);

        //写入日志
        /*try {
            Thread insertLog=new ThreadInsertLog("更新携程订单实时状态池-updateOrderResult()",switchOrderPool);
            insertLog.start();
        }catch (Exception logE){
            log.info("写入日志异常，请检查！");
        }*/
    }

    /**
     * pool 表订单状态日志保存
     * qiuyy  202020907
     * @param orderId
     * @param sysState
     * @param mtState
     * @param isOrder
     * @param remark
     */
    public void insertPoolStateHistroy(String orderId,Integer sysState,String mtState,Integer isOrder,String remark){
        SwitchsPoolOrderStateHistory switchsPoolOrderStateHistory = new SwitchsPoolOrderStateHistory();
        switchsPoolOrderStateHistory.setId(StringUtil.getUUID());
        switchsPoolOrderStateHistory.setOrderId(orderId);
        switchsPoolOrderStateHistory.setCreateTime(new Date());
        switchsPoolOrderStateHistory.setIsOrder(isOrder);
        switchsPoolOrderStateHistory.setSysStatus(sysState);
        switchsPoolOrderStateHistory.setRemark(remark);
        if(null != mtState){
            switchsPoolOrderStateHistory.setMtStatus(Integer.valueOf(mtState));
        }
        try{
            switchsPoolOrderStateHistoryMapper.insert(switchsPoolOrderStateHistory);
        }catch (Exception e){
            log.error("switchsPoolOrderStateHistoryMapper 保存异常："+e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 携程修改库存接口
     */
    private void switchModifyRemain(String switchsHotelId,String roomId,String checkinDate,String checkoutDate, Integer checkVoRemainRoomNum) {
        //库存数量 如果返回999 库存设置为10 返回1-5设置为5,返回0为0
        //version qyy  调用美团的预下单效验更改，如果返回999设置为10，返回1-5就根据返回的具体数量传过来
        int num;
        if (checkVoRemainRoomNum == 999) {
            num = 5;
        }else{
            num = checkVoRemainRoomNum;
        } /*else if (1 <= checkVoRemainRoomNum && checkVoRemainRoomNum <= 5) {
            num = 5;
        } else {
            num = 0;
        }*/
        //请求参数
        ModifyRemainVo modifyRemainVo = new ModifyRemainVo();
        modifyRemainVo.setHotelId(Integer.valueOf(switchsHotelId));
        modifyRemainVo.setRoomId(Integer.valueOf(roomId));
        modifyRemainVo.setNum(num);
        modifyRemainVo.setTime(DateUtil.switchDateParse(checkinDate));
        modifyRemainVo.setEndTime(DateUtil.switchDateParse(checkoutDate));
        try {
            log.info("修改库存  switchModifyRemain 请求参数： {}", JSON.toJSONString(modifyRemainVo));
            Result<Object> result = switchPushRoomService.modifyRemain(modifyRemainVo);
            log.info("修改库存  switchModifyRemain 响应参数： {}", JSON.toJSONString(result));
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
    *@Description: 新订单, 延住(重新下单)操作
     *      * 将数据添加入 订单池中 switch_order_pool
    *@Param:
    *@return: Result<SwitchOrderPool>
    *@Author: Zhang·jz
    *@date: 2020/9/14
    */
    public Result<Object> insertNewOperateSwitchAndMeituanOrderNew(SwitchOrderListNotify switchOrderListNotify, String dltOrderId, Result<Object> orderDetailResult){
        log.info("开始校验订单列表，并将数据新增至 订单池---进入新订单,延住(重新下单)操作--insertNewOperateSwitchAndMeituanOrderNew>");
        Result<Object> ret = new Result<>();

        //订单详情读取成功；
        String orderId = switchOrderListNotify.getOrderId();
        if(ObjectUtils.isEmpty(orderId)){

            ret.setCode(CommonConstants.SUCCESS);
            ret.setMsg("订单id 为空 ，不做新增到订单池!");
            ret.setData(new SwitchOrderPool());
            return ret;
        }
        String reMark = "" ;//修改备注
        if(orderDetailResult.getCode()==CommonConstants.SUCCESS){

            //会生成两个订单，但是订单号一样，代理通订单号不一样 保证订单池中当条订单的数据唯一
            SwitchOrderPool switchOrderPool = switchOrderPoolMapper.findOrderBySwitchOrderId(orderId);
            String poolAction = "Insert";//新增
            //判断是否存在当前订单,新订单默认为立即下单
            if(ObjectUtils.isEmpty(switchOrderPool) || ObjectUtils.isEmpty(switchOrderPool.getId())){
                switchOrderPool = new SwitchOrderPool();
                switchOrderPool.setId(StringUtil.getUUID());
                switchOrderPool.setDltOrderId(dltOrderId);
                switchOrderPool.setCreateTime(new Date());
                switchOrderPool.setState(0);//默认正常数据
                switchOrderPool.setMtOrderState("0");//美团默认状态 待下单
                switchOrderPool.setSysOrderState(0);//系统订单状态 0：待确认(携程订单校验通过)； 1：已确认（校验通过，已下单）；  2：拒绝（校验不通过）；  3：完成（订单交易完成）； 4：取消；
                log.info("insertNewOperateSwitchAndMeituanOrderNew（orderId="+orderId+"）  : 立即下单，IsOrder状态修改为1!------>");
                switchOrderPool.setIsOrder(1);//可立即下单
                switchOrderPool.setRemark(String.valueOf(new Date()) + "订单池新增");
            }else{
                poolAction = "update";//修改
                //如果是延时单则会继续调用当前方法，并调用校验接口是否可以采购；如果可以采购则修改延时单为立即下单； isOrder = 1
                MtHotelOrderCheckParamVo mtHotelOrderCheckParamVo = new MtHotelOrderCheckParamVo();
                SwitchCreateRoomDto switchCreateRoomDto = switchCreateRoomService.getMtInfoBySwitchRoomId(Integer.valueOf(roomId));

                //根据订单号查询当前订单表信息
                Map switchOrderInfoMap = new HashMap();
                switchOrderInfoMap.put("orderId",orderId);
                SwitchOrderInfo switchOrderInfo = switchOrderInfoMapper.findOneByOrderId(switchOrderInfoMap);


                log.info("insertNewOperateSwitchAndMeituanOrderNew --switchCreateRoomDto--->{}",switchCreateRoomDto);
                mtHotelOrderCheckParamVo.setHotelId(Long.valueOf(switchCreateRoomDto.getMtHotelId()));
                mtHotelOrderCheckParamVo.setGoodsId(switchCreateRoomDto.getMtGoodId());
                mtHotelOrderCheckParamVo.setCheckinDate(DateUtil.switchDateParse(switchOrderInfo.getCheckinDate()));
                mtHotelOrderCheckParamVo.setCheckoutDate(DateUtil.switchDateParse(switchOrderInfo.getCheckoutDate()));
                mtHotelOrderCheckParamVo.setRoomNum(switchOrderInfo.getRoomnum());
                mtHotelOrderCheckParamVo.setTotalPrice(switchOrderInfo.getOrderPrice().multiply(new BigDecimal(100)).intValue());

                String dataJson = JacksonUtil.objectToJson(mtHotelOrderCheckParamVo);
                log.info("insertNewOperateSwitchAndMeituanOrderNew --开始调用美团校验是否可以下单---dataJson--->{}",dataJson);
                //调用美团校验是否可以下单
                Result checkOrderPriceResult = new Result();
                checkOrderPriceResult = RestTemplateUtils.post(CommonUrlConstants.MEITUAN_HOST+"/mtHotelOrderDeal/checkOrderPrice",dataJson,restTemplate);
                log.info("insertNewOperateSwitchAndMeituanOrderNew --调用美团校验是否可以下单结果---checkOrderPriceResult--->{}",checkOrderPriceResult);
//                checkOrderPriceResult.setCode(CommonConstants.SUCCESS);
                //如果校验成功则修改为立即下单 idsOrder =1
                if(checkOrderPriceResult.getCode() == CommonConstants.SUCCESS){
                    log.info("insertNewOperateSwitchAndMeituanOrderNew（orderId="+orderId+"）  : 立即下单，IsOrder状态修改为1!------>");
                    switchOrderPool.setIsOrder(1);//可立即下单
                    switchOrderPool.setRemark(switchOrderPool.getRemark()+ ";" + String.valueOf(new Date()) + "修改为立即下单，IsOrder状态修改为1!");
                }
            }
            log.info("insertNewOperateSwitchAndMeituanOrderNew（orderId="+orderId+"）  poolAction----->{}",poolAction);

            switchOrderPool.setModifyTime(new Date());
            switchOrderPool.setMd5Key(switchOrderListNotify.getMd5Key());//设置md5
            switchOrderPool.setOrderId(switchOrderListNotify.getOrderId());//设置订单号

            this.insertPoolStateHistroy(switchOrderPool.getOrderId(),switchOrderPool.getSysOrderState(),
                    switchOrderPool.getMtOrderState(),switchOrderPool.getIsOrder(),DateUtil.getCurrTime()+" insertNewOperateSwitchAndMeituanOrderNew:"+reMark);

            int retInt = 0;
            if("Insert".equals(poolAction)){
                retInt =  switchOrderPoolMapper.insert(switchOrderPool);
            }else{
                retInt =  switchOrderPoolMapper.updateOrderStateByPK(switchOrderPool);

            }

            if(retInt == -1){

                if("Insert".equals(poolAction)){
                    reMark =  "携程新增订单操作数据库失败 - insertNewOperateSwitchAndMeituanOrderNew";
                }else{
                    reMark =  "携程修改订单操作数据库失败 - insertNewOperateSwitchAndMeituanOrderNew";
                }
                log.info("insertNewOperateSwitchAndMeituanOrderNew（orderId="+orderId+"）  {} switchOrderPool---> {} ",reMark,switchOrderPool);
                return new Result<>(CommonConstants.ERROR,"订单新增/修改失败 ，请检查! ",switchOrderPool);
            }

            ret.setCode(CommonConstants.SUCCESS);
            ret.setMsg("校验成功，可以进行下单操作!");
            ret.setData(switchOrderPool);
            log.info(" insertNewOperateSwitchAndMeituanOrderNew（orderId="+orderId+"）  订单操作数据成功!------>");
        }else{//调用失败

            //写入日志
            try {
                Thread insertLog=new ThreadInsertLog("携程新增订单操作失败 - insertNewOperateSwitchAndMeituanOrderNew",orderDetailResult);
                insertLog.start();
            }catch (Exception e){
                log.info("写入日志异常，请检查！");
            }
            return new Result<>(orderDetailResult);
        }

        return ret;
    }

    /**
     * 新订单,延住(重新下单)操作
     * 将数据添加入 订单池中 switch_order_pool
     *
     * @param switchOrderListNotify
     * @param dltOrderId
     * @param orderDetailResult
     * @return
     */
    public Result<Object> insertNewOperateSwitchAndMeituanOrder(SwitchOrderListNotify switchOrderListNotify, String dltOrderId, Result<Object> orderDetailResult){
        log.info("开始校验订单列表，并将数据新增至 订单池---进入新订单,延住(重新下单)操作--insertNewOperateSwitchAndMeituanOrder>");
        String token = "";//HttpClientBaseAuth.getAuthToken();
        Result<Object> ret = new Result<>();
//        SwitchOrderListNotify switchOrderListNotify = switchOrderListNotifyMapper.findSwitchOrderListNotifyByMd5Key(md5Key);
//        if(ObjectUtils.isEmpty(switchOrderListNotify)){
//            return new Result<>(CommonConstants.ERROR);
//        }
//        String dltOrderId = switchOrderListNotify.getDltOrderId();//代理同订单id

//        //不为空继续操作
//        //1：先根据订单号，获取订单详细信息；为了获取到对应酒店id 和房型id
//        Result<Object> orderDetailResult= getdltorderinfo(dltOrderId);
//        log.info("orderDetailResult----->{}",orderDetailResult);

        //订单详情读取成功；
        //2：进行订单校验  返回状态： 0：成功； 1：价格上浮 2：网络异常 3：库存不够
        Result<Object> objectValidPriceResult = null;
        //调用美团预下单接口进行校验(2020-07-25)
        Result<Object> objectMeituanValidPriceResult = null;
        String orderId = switchOrderListNotify.getOrderId();
        String reMark = "" ;//修改备注
        if(orderDetailResult.getCode()==CommonConstants.SUCCESS){

            log.info("orderDetailResult.getCode()----->{}",orderDetailResult.getCode());
            ValidPriceVo validPriceVo = new ValidPriceVo();
            validPriceVo.setHotelId(Integer.valueOf(hotelId));
            validPriceVo.setRoomId(Integer.valueOf(roomId));
            validPriceVo.setTime(time);
            validPriceVo.setPrice(price);
            validPriceVo.setEndTime(endTime);
            validPriceVo.setNum(num);

            //会生成两个订单，但是订单号一样，代理通订单号不一样 保证订单池中当条订单的数据唯一
            SwitchOrderPool switchOrderPool = switchOrderPoolMapper.findOrderBySwitchOrderId(orderId);
            String poolAction = "Insert";//新增
            //判断是否存在当前订单
            if(ObjectUtils.isEmpty(switchOrderPool) || ObjectUtils.isEmpty(switchOrderPool.getId())){
                switchOrderPool = new SwitchOrderPool();
                switchOrderPool.setId(StringUtil.getUUID());
                switchOrderPool.setDltOrderId(dltOrderId);
                switchOrderPool.setCreateTime(new Date());
                switchOrderPool.setState(0);//默认正常数据
                switchOrderPool.setMtOrderState("0");//美团默认状态 待下单
            }else{
                poolAction = "update";//修改
            }

            log.info("poolAction----->{}",poolAction);
            try {

                log.info("validPriceVo----> : {} ",JacksonUtil.objectToJson(validPriceVo));
                objectValidPriceResult = switchPushRoomService.validStatus(validPriceVo);
                log.info("将数据新增至 订单池-1:校验酒店信息：objectValidPriceResult---调用酒店相关信息校验返回值-->{}",objectValidPriceResult);


                //校验成功，可以开始调用美团预下单（更新携程库存接口调用）
                if(Integer.valueOf(objectValidPriceResult.getData().toString()) == 0){

                    log.info("将数据新增至 订单池-1.1:校验酒店信息《《成功》》-->");
                    if(ObjectUtils.isEmpty(switchOrderPool.getSysOrderState()) || switchOrderPool.getSysOrderState() != 1){//判断如果系统状态为 1 携程接受订单，则不做修改
                        switchOrderPool.setSysOrderState(0);//系统订单状态 0：待确认(携程订单校验通过)； 1：已确认（校验通过，已下单）；  2：拒绝（校验不通过）；  3：完成（订单交易完成）； 4：取消；'
                    }

                    SwitchCreateRoomDto switchCreateRoomDto = switchCreateRoomService.getMtInfoBySwitchRoomId(Integer.valueOf(roomId));
                    int retCount = 0;
                    while(ObjectUtils.isEmpty(switchCreateRoomDto) && retCount <3){
                        retCount++;
                        switchCreateRoomDto = switchCreateRoomService.getMtInfoBySwitchRoomId(Integer.valueOf(roomId));
                    }
                    //校验成功将当前订单数据存储到订单池，再次校验该房型再美团中是否可以立即下单
                    // (如果美团中不可取消，则携程订单需要等待9（CommonConstants.SWITCH_ORDER_WAIT_TIME）分钟后再对美团酒店进行采购)
                    Result<Object> objectResult = new Result<>();

                    try {
                        //请求参数
                        Map<String, Object> dataMap = new HashMap<>();
                        dataMap.put("mtHotelId", switchCreateRoomDto.getMtHotelId());
                        dataMap.put("mtGoodsId", switchCreateRoomDto.getMtGoodId());
                        dataMap.put("checkinDate", time);
                        String dataJson = JacksonUtil.objectToJson(dataMap);

                        log.info("将数据新增至 订单池-2:校验美团酒店是否可取消!------>");
                        //调用美团判断该商品是否可取消
                        objectResult = RestTemplateUtils.post(CommonUrlConstants.MEITUAN_HOST+"/mtHotelGoodsRule/checkGoodsCancel",dataJson,restTemplate);
                        log.info("objectResult ： {}",objectResult);
                    }catch (Exception e){//接口调用异常
                        return new Result<>(CommonConstants.ERROR,e.getMessage());
                    }


                    log.info("校验成功，美团酒店不可取消!------>");

                    log.info("将数据新增至 订单池-3:校验调用美团下单前校验!------>");
                    //调用美团预下单接口进行校验(2020-07-25) 不可取消订单直接如果下单前校验通过(0，8（价格下调）)则通知携程立即接单，如果不通过则不做操作可以拒绝并做延时10分钟（继续调用美团查看是否有房）
                    Result switchOrderOperateResult = switchOrderOperateService.getSwitchOrderInfoByDltByOrderId(orderId);
                    log.info("switchOrderOperateResult---->>> {}",switchOrderOperateResult);
                    SwitchOrderInfoDto switchOrderInfoDto = JacksonUtil.objToBean(switchOrderOperateResult.getData(), SwitchOrderInfoDto.class);

                    log.info("switchOrderInfoDto---调用美团预下单接口进行校验-->{}",switchOrderInfoDto);
                    objectMeituanValidPriceResult = meituanCheckOrder(token,switchOrderInfoDto);
                    log.info("objectMeituanValidPriceResult---调用美团预下单接口进行校验-->{}",objectMeituanValidPriceResult);
                    //校验结果码： 0 校验成功 1 校验失败 2 黑名单酒店  3 房态不满足预订  4 三方产品不可售  5 产品不存在  6 产库存不足  7 未获取到价格  8 价格发生变化  非空：是
//                        MtHotelOrderCheckVo mtHotelOrderCheckVo = (MtHotelOrderCheckVo) objectMeituanValidPriceResult.getData();
                    MtHotelOrderCheckVo mtHotelOrderCheckVo = JacksonUtil.objToBean(objectMeituanValidPriceResult.getData(),MtHotelOrderCheckVo.class);
                    log.info("调用美团预下单接口进行校验,返回mtHotelOrderCheckVo -->{}",mtHotelOrderCheckVo);
                    //判断下单前校验返回值,不为空
                    if(!ObjectUtils.isEmpty(mtHotelOrderCheckVo) && !ObjectUtils.isEmpty(mtHotelOrderCheckVo.getCode())){

                        //再次调用携程校验接口，做美团下单前校验状态的各个状态校验
//                              Result retTemp = updateSwitchsOrderByMtBookingBeforeCode(switchOrderInfoDto,mtHotelOrderCheckVo);
                        Result retTemp = checkBookingOrderResult(switchOrderInfoDto,mtHotelOrderCheckVo);
                        log.info("再次调用携程校验接口，做美团下单前校验状态的各个状态校验,返回-->{}",retTemp);
                        if(retTemp.getCode() == CommonConstants.SUCCESS){//可下单

                            log.info("将数据新增至 订单池-4:美团下单前校验 调用成功，可下单，系统状态修改为0(可立即下单)!------>");
                            if((boolean)objectResult.getData()){//返回true 可取消，则可以立即下单

                                log.info("将数据新增至 订单池-2-1: 校验美团酒店：可取消，立即下单，系统状态修改为0!------>");
                                switchOrderPool.setIsOrder(1);//可立即下单

                            }else {//不可取消；等待10分钟【2020-07-25 携程酒店订单立即接受，但是延时向美团下单】

                                log.info("将数据新增至 订单池-2-2:校验美团酒店：不可取消，修改为可立即下单，系统状态修改为0；2020/8/24------>");
                                /**
                                *@Description: 修改为立即下单
                                *@Author: Zhang·jz
                                *@date: 2020/8/24
                                */
                                switchOrderPool.setIsOrder(1);//可立即下单
                                //如果不是延时状态的做操作
//                                log.info("将数据新增至 订单池-2-2:校验美团酒店：不可取消，立即操作携程接口，接受订单；并延时5分钟后向美团下单------>");
//                                if(ObjectUtils.isEmpty(switchOrderPool.getIsOrder()) || switchOrderPool.getIsOrder() != 0) {//不是延时下单
//                                    switchOrderPool.setIsOrder(0);//延时下单
//                                    switchOrderPool.setOrderWaitTime(CommonConstants.SWITCH_ORDER_MT_NOCENCAL_WAIT_TIME);//等待时长(分钟)
//
//                                    if(ObjectUtils.isEmpty(switchOrderPool.getSysOrderState()) || switchOrderPool.getSysOrderState() != 1) {
//                                        //调用操作携程订单
//                                        OperateDltOrder operateDltOrder = new OperateDltOrder();
//                                        //下单成功，接受订单
//                                        operateDltOrder.setOperaterType(0);
//                                        //按入1住人姓名 2按确认号
//                                        operateDltOrder.setConfirmType(2);
//
//                                        operateDltOrder.setOrderId(switchOrderPool.getOrderId());
//                                        //请求携程订单操作接口
//                                        Result result = operaterDltOrder(operateDltOrder);
//                                        log.info("将数据新增至 订单池-2-3:校验美团酒店：不可取消，立即操作携程接受订单，返回值------> {}",result);
//                                        if (result.getCode() == CommonConstants.SUCCESS) {//反馈成功。系统订单状态变更为 1已确认
//
//                                            log.info("将数据新增至 订单池-2-4:校验美团酒店：立即操作携程接受订单，返回《《成功》》，并修改订单池订单状态为1；订单定时任务不再次操作该订单携程状态------> ");
//                                            switchOrderPool.setSysOrderState(1);
//                                        } else {//如果失败，定时任务会继续调用当前订单进行操作 系统订单状态变更为 0已确认
//                                            log.info("将数据新增至 订单池-2-5:校验美团酒店：立即操作携程接受订单，返回《《失败》》，并修改订单池订单状态为0；订单定时任务需要再次操作该订单携程状态------> ");
//                                            switchOrderPool.setSysOrderState(0);
//                                        }
//                                    }
//                                }

                                //如果状态是10 则说明原来是携程已接受订单；则当前状态需改回 1
//                                if(!ObjectUtils.isEmpty(switchOrderPool.getSysOrderState()) && switchOrderPool.getSysOrderState() == 10) {
//                                    switchOrderPool.setSysOrderState(1);//将系统订单状态修改1
//                                }

                            }
                            //如果规则做变更了--情况少，埋点--如果状态是10 则说明原来是携程已接受订单；则当前状态需改回 1
                            if(!ObjectUtils.isEmpty(switchOrderPool.getSysOrderState()) && switchOrderPool.getSysOrderState() == 10) {//如果状态是10 则说明原来是携程已接受订单；则当前状态需改回 1
                                switchOrderPool.setSysOrderState(1);//将系统订单状态修改1
                            }
                        }else{//不可下单，延时订单等待再次校验；说明是下单前校验失败则将订单状态修改为10 ，美团校验失败，携程已接受订单

                            log.info("将数据新增至 订单池-3-1:校验调用美团下单前校验<<失败>>,系统状态修改2(拒绝)；可能库存不足等原因；延时10分钟下单!------>");
                            switchOrderPool.setSysOrderState(SwitchOrderPoolStateEnums.REFUSE.getCode());//拒单

                            if(!ObjectUtils.isEmpty(switchOrderPool.getSysOrderState()) && switchOrderPool.getSysOrderState() == 1) {//原来是携程已接受订单
                                switchOrderPool.setSysOrderState(10);//将系统订单状态修改10，等待人工处理
                            }

                            if(ObjectUtils.isEmpty(switchOrderPool.getIsOrder()) || switchOrderPool.getIsOrder() != 0) {//IsOrder== 0说明原状态就是延时下单，不需要重复修改

                                switchOrderPool.setIsOrder(0);//延时下单
                                switchOrderPool.setOrderWaitTime(CommonConstants.SWITCH_ORDER_WAIT_TIME);//等待时长(分钟)
                                SendUtils.dingMsgOrder("[INSERTNEW] 订单将延迟处理 ", cn.hutool.core.date.DateUtil.now()+"："+JacksonUtil.objectToJson(retTemp)+"，订单号="+orderId, MessageEnums.genre.DELAYED_ORDER.getCode(),orderId,restTemplate);
                            }
                            reMark = reMark + " 携程订单状态为“拒单（2）”；再次调用携程校验接口，做美团下单前校验状态的各个状态校验,返回 retTemp -->{"+JacksonUtil.objectToJson(retTemp)+"}";

                        }
                    }else{//下单前校验返回值为空，可能接口失败等原因；不可下单，进入延时订单等待再次校验

                        log.info("将数据新增至 订单池-3-1:下单前校验返回值为空，可能接口失败等原因<<失败>>,系统状态修改2(拒绝)；不可下单，进入延时订单等待再次校验；延时10分钟!------>");

                        switchOrderPool.setSysOrderState(SwitchOrderPoolStateEnums.REFUSE.getCode());//拒单
                        //IsOrder== 0 说明原状态就是延时下单，不需要重复修改
                        if(ObjectUtils.isEmpty(switchOrderPool.getIsOrder()) || switchOrderPool.getIsOrder() != 0) {// if(switchOrderPool.getSysOrderState() != 1) 原来是携程已接受订单，则当前状态可不做变更等待再次调用
                            switchOrderPool.setIsOrder(0);//延时下单
                            switchOrderPool.setOrderWaitTime(CommonConstants.SWITCH_ORDER_WAIT_TIME);//等待时长(分钟)
                            SendUtils.dingMsgOrder("[INSERTNEW-CHECK] 订单将延迟处理 ", cn.hutool.core.date.DateUtil.now()+"："+JacksonUtil.objectToJson(mtHotelOrderCheckVo)+"，订单号="+switchOrderPool.getOrderId(), MessageEnums.genre.DELAYED_ORDER.getCode(),orderId,restTemplate);
                        }

                        if(!ObjectUtils.isEmpty(switchOrderPool.getSysOrderState()) && switchOrderPool.getSysOrderState() == 1) {//原来是携程已接受订单
                            switchOrderPool.setSysOrderState(10);//将系统订单状态修改10，等待人工处理
                        }
                        reMark = reMark + " 携程订单状态为“拒单（2）”；调用美团预下单接口进行校验,返回 mtHotelOrderCheckVo -->{"+JacksonUtil.objectToJson(mtHotelOrderCheckVo)+"}";

                    }



                    ret.setCode(CommonConstants.SUCCESS);
                    ret.setMsg("校验成功，可以进行下单操作!");

                    log.info("校验成功，可以进行下单操作!------>");

                }else{//其他状态 1 美团价格上浮 ，2 调用接口网络异常，3  美团库存不足  4 美团产品信息未找到  ---  拒单，并做携程对应房型设置库存为0/满房；不做下架处理
                    log.info("将数据新增至 订单池-1-2:校验酒店信息《《失败》》,系统状态修改2(拒绝)，修改为延时单-->");
//                    return new Result<>(CommonEnums.SWITCH_ORDER_REFUSE_OPERATE);
                    switchOrderPool.setSysOrderState(SwitchOrderPoolStateEnums.REFUSE.getCode());
                    //20200720-增加当前延时拒单状态，如果不是延时单
                    if(ObjectUtils.isEmpty(switchOrderPool.getIsOrder()) || switchOrderPool.getIsOrder() != 0){
                        switchOrderPool.setIsOrder(0);//延时下单
                        switchOrderPool.setOrderWaitTime(CommonConstants.SWITCH_ORDER_WAIT_TIME);//等待时长(分钟)
                    }

                    ret.setMsg(CommonEnums.SWITCH_ORDER_REFUSE_OPERATE.getMsg()+"--调用携程校验接口返回："+ JacksonUtil.objectToJson(objectValidPriceResult));
                    ret.setCode(CommonEnums.SWITCH_ORDER_REFUSE_OPERATE.getCode());
                    reMark = reMark + " 携程订单状态为“拒单（2）”；调用携程校验接口返回 -->{"+JacksonUtil.objectToJson(objectValidPriceResult)+"}";
                    log.info("校验失败!请确认校验接口是否返回正常值------>");
                }

                switchOrderPool.setRemark(String.valueOf(new Date()) + reMark);
                switchOrderPool.setModifyTime(new Date());
                switchOrderPool.setMd5Key(switchOrderListNotify.getMd5Key());//设置md5
                switchOrderPool.setOrderId(switchOrderListNotify.getOrderId());//设置订单号

                this.insertPoolStateHistroy(switchOrderPool.getOrderId(),switchOrderPool.getSysOrderState(),
                        switchOrderPool.getMtOrderState(),switchOrderPool.getIsOrder(),DateUtil.getCurrTime()+" insertNewOperateSwitchAndMeituanOrder:"+reMark);

                int retInt = 0;
                if("Insert".equals(poolAction)){
                    retInt =  switchOrderPoolMapper.insert(switchOrderPool);
                }else{
//                    switchOrderPoolMapper.updateOrderResult(switchOrderPool);
                    retInt =  switchOrderPoolMapper.updateByPrimaryKey(switchOrderPool);
                }

                if(retInt == -1){
                    String retMark = "";
                    if("Insert".equals(poolAction)){
                        retMark =  "携程新增订单操作数据库失败 - insertNewOperateSwitchAndMeituanOrder";
                    }else{
                        retMark =  "携程修改订单操作数据库失败 - insertNewOperateSwitchAndMeituanOrder";
                    }
                    log.info(" {} switchOrderPool---> {} ",retMark,switchOrderPool);
                    //写入日志
                    try {
                        Thread insertLog=new ThreadInsertLog(retMark,orderDetailResult);
                        insertLog.start();
                    }catch (Exception e){
                        log.info("写入日志异常，请检查！");
                    }
                    return new Result<>(CommonConstants.ERROR,"订单新增/修改失败 ，请检查! ",switchOrderPool);
                }

                log.info("订单操作数据成功!------>{}",poolAction);
                ret.setData(switchOrderPool);
            } catch (Exception e) {
                log.error(e.getMessage(),e);
//                e.printStackTrace();

                //写入日志
                try {
                    Thread insertLog=new ThreadInsertLog("携程新增订单操作异常 - insertNewOperateSwitchAndMeituanOrder",e.getMessage());
                    insertLog.start();
                }catch (Exception logE){
                    log.info("写入日志异常，请检查！");
                }
                return new Result<>(CommonEnums.SWITCH_ORDER_COMPARE_VALID_PRICE,e.getMessage());
            }
        }else{//调用失败

            //写入日志
            try {
                Thread insertLog=new ThreadInsertLog("携程新增订单操作失败 - insertNewOperateSwitchAndMeituanOrder",orderDetailResult);
                insertLog.start();
            }catch (Exception e){
                log.info("写入日志异常，请检查！");
            }
            return new Result<>(orderDetailResult);
        }

        //写入日志
        /*try {
            Thread insertLog=new ThreadInsertLog("携程新增订单操作成功 - insertNewOperateSwitchAndMeituanOrder",ret);
            insertLog.start();
        }catch (Exception e){
            log.info("写入日志异常，请检查！");
        }*/
        return ret;
    }


    /**
     * 调用美团下单前校验
     * @param accessToken
     * @param switchOrderInfoDto
     * @return
     */
    public Result meituanCheckOrder(String accessToken, SwitchOrderInfoDto switchOrderInfoDto) {
        log.info("进入调用美团下单前校验--meituanCheckOrder--> {}",switchOrderInfoDto);
        String orderCheckUrl = CommonUrlConstants.MEITUAN_HOST + UrlSwitchsEnums.switchOrderPool.POST_MT_ORDER_CHECK.getValue();//+ "?access_token=" + accessToken;

        log.info("进入调用美团下单前校验--orderCheckUrl-->{}",orderCheckUrl);
        //调用美团下单前校验接口
//        Result checkOrderResult = meituanCheckOrder(orderCheckUrl, switchOrderInfoDto);

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.valueOf("application/json;UTF-8"));
        //请求参数
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("hotelId", switchOrderInfoDto.getMtHotelId());
        dataMap.put("goodsId", switchOrderInfoDto.getGoodsId());
        String checkinDate = DateUtil.switchDateParse(switchOrderInfoDto.getCheckinDate());
        String checkoutDate = DateUtil.switchDateParse(switchOrderInfoDto.getCheckoutDate());
        log.info("进入调用美团下单前校验时间格式--checkinDate--> {}",checkinDate);
        log.info("进入调用美团下单前校验时间格式--checkoutDate--> {}",checkoutDate);

        dataMap.put("checkinDate", checkinDate);
        dataMap.put("checkoutDate", checkoutDate);
        dataMap.put("roomNum", switchOrderInfoDto.getRoomnum());
        dataMap.put("totalPrice", switchOrderInfoDto.getTotalPrice());
        String dataJson = JacksonUtil.objectToJson(dataMap);
        //获取携程订单实时状态池信息
        Result response = RestTemplateUtils.post(orderCheckUrl,dataJson,restTemplate);
        log.info("进入调用美团下单前校验--response-->{}",response);
        return response;
    }


    /**
     * 携程订单取消操作
     * 先取消美团，再取消携程
     *
     * @param switchOrderListNotify
     * @param dltOrderId
     * @return
     */
    public Result<Object> cancelNewOperateSwitchAndMeituanOrder(SwitchOrderListNotify switchOrderListNotify, String dltOrderId){
        log.info("开始校验订单列表111，携程订单取消操作--cancelNewOperateSwitchAndMeituanOrder>");

        Result<Object> objectResult = new Result<>();
        SwitchOrderPool switchOrderPool = switchOrderPoolMapper.findOrderBySwitchOrderId(switchOrderListNotify.getOrderId());
        log.info("switchOrderPool-->>{}",switchOrderPool);

        //订单备注
        String remarkStr = "";
        //判断美团中是否已下单；如果下单则分为；
//        if(null != switchOrderPool && !ObjectUtils.isEmpty(switchOrderPool.getMeituanOrderId()) ){//美团订单不为空则美团中已提交
        //20200-09-09 18:58 根据携程订单状态(2),美团订单状态(0),是延时单(0) , 说明美团没有下单成功，如果携程推送用户取消订单，则立即接受取消；
        if(ObjectUtils.isEmpty(switchOrderPool) || (switchOrderPool.getSysOrderState() == 2 && "0".equals(switchOrderPool.getMtOrderState()) && switchOrderPool.getIsOrder() == 0) ){
            log.info("美团中没有下单----->");
            String optState = "";//操作新增还是修改
            if(ObjectUtils.isEmpty(switchOrderPool)){//异常订单数据，为做接受订单数据，直接获取到取消订单数据；
                optState = "insert";
                log.info("异常订单数据，为做接受订单数据，直接获取到取消订单数据-->>{}",switchOrderPool);
                switchOrderPool = new SwitchOrderPool();
                switchOrderPool.setId(StringUtil.getUUID());
                switchOrderPool.setCreateTime(new Date());
                switchOrderPool.setState(1);
                switchOrderPool.setRemark("不存在接收订单数据");

            }
            remarkStr = "操作时间："+DateUtil.getNowTime()+ " 美团订单不存在，则未向美团下单，直接接受取消;  "+switchOrderPool.getRemark();
            switchOrderPool.setSysOrderState(7);//7：接受取消(携程)
            switchOrderPool.setMtOrderState("0");//0：美团订单状态修改为0  （2020-09-09 17:10）美团没采购成功，携程那边取消；系统应自动接受取消
            switchOrderPool.setRemark(remarkStr);
            switchOrderPool.setIsOrder(1);//用户取消，立即接受取消
            switchOrderPool.setIsOrderRemark("携程用户取消，立即接受取消");

            if("insert".equals(optState)){//如果订单池不存在当前订单，新增并做接受取消
                switchOrderPoolMapper.insert(switchOrderPool);
            }

            //version qiuyy  20200907 独立增加pool订单日志保存表
            this.insertPoolStateHistroy(switchOrderPool.getOrderId(),switchOrderPool.getSysOrderState(),
                    switchOrderPool.getMtOrderState(),switchOrderPool.getIsOrder(),DateUtil.getCurrTime()+" cancelNewOperateSwitchAndMeituanOrder:"+switchOrderPool.getRemark());


        }else{//正常已向美团下单，做正常取消流程

            log.info("美团中已下单----->");
            //判断美团订单状态是否为 用户已入住：50 ，如果是用户已入住则直接拒绝取消 2020-09-01 修改
            if("50".equals(switchOrderPool.getMtOrderState())){
                remarkStr = "美团订单异步通知用户已入住；状态为：50";
                switchOrderPool.setSysOrderState(8);//8：拒绝取消(携程)
                switchOrderPool.setRemark(remarkStr);
                objectResult.setCode(CommonEnums.SWITCH_ORDER_COMPARE_VALID_PRICE.getCode());
                objectResult.setMsg(remarkStr);
            }else{
                Map mtHotelOrderCancelParamVo = new HashMap();
                mtHotelOrderCancelParamVo.put("distributorOrderId",switchOrderPool.getMtDistributorOrderId());
                mtHotelOrderCancelParamVo.put("mtOrderId",switchOrderPool.getMeituanOrderId());

                //已下单取消分为：1:待确认取消（直接调用美团取消订单接口；1：未确认预定尝试取消；） 0：正常取消
                if(!switchOrderPool.getMtOrderState().equals(MtHotelEnums.orderStateEnum.BOOKINGSUCCSS.getCode())){//不等于预定成功的数据，则可以直接取消
                    if(switchOrderPool.getMtOrderState().equals(MtHotelEnums.orderStateEnum.BOOKING)){//预定中则取消
                        mtHotelOrderCancelParamVo.put("cancelReason","其它");
                        mtHotelOrderCancelParamVo.put("cancelCheck",1);
                    }else{
                        mtHotelOrderCancelParamVo.put("cancelReason","行程变更");
                        mtHotelOrderCancelParamVo.put("cancelCheck",0);
                    }
                }else{//预定成功，接口会提交正常取消数据，并请走人工客服；
                    mtHotelOrderCancelParamVo.put("cancelReason","行程变更");
                    mtHotelOrderCancelParamVo.put("cancelCheck",0);
                }
                objectResult = RestTemplateUtils.post(CommonUrlConstants.MEITUAN_HOST+"/mtHotelOrder/orderCancel",JacksonUtil.objectToJson(mtHotelOrderCancelParamVo),restTemplate);
                log.info("objectResult--->>{}",objectResult);
                Map retMap = (Map) objectResult.getData();//解析对象
                switchOrderPool.setRemark(retMap.toString());
                //携程订单取消提交
                /**
                 * 取消订单返回码：
                 * 0 取消成功
                 * 1 系统繁忙
                 * 2 取消失败（超过最晚可取消时间；用户已入住等原因）
                 * 3 订单号不存在
                 * 4 取消失败，产品不允许取消
                 * 5 订单取消中
                 * 10 订单已经确认
                 * 20 其它
                 */
                if(0 == Integer.valueOf(retMap.get("code").toString())){//返回成功，则取消成功/取消中

                    switchOrderPool.setSysOrderState(7);//7：接受取消(携程)
                    switchOrderPool.setMtOrderState(String.valueOf(MtHotelEnums.orderStateEnum.CANCELSUCCSS.getCode()));//31：取消成功

                }else if(5 == Integer.valueOf(retMap.get("code").toString())){//美团取消中，订单池系统状态设置取消中，等待美团异步回调修改状态
                    switchOrderPool.setSysOrderState(5);//5：取消中
                    switchOrderPool.setMtOrderState(String.valueOf(MtHotelEnums.orderStateEnum.CANCELING.getCode()));//30：取消中

                }else {//美团取消失败，设置状态为美团取消失败，人工客服联系;原美团订单状态不做变更
                    switchOrderPool.setSysOrderState(8);//8：拒绝取消(携程)
                    switchOrderPool.setMtOrderState(String.valueOf(MtHotelEnums.orderStateEnum.CANCELFAILED.getCode()));//32：取消失败
                    //推送消息至钉钉群,存在异常订单
                    try {
                        String title = "携程拒绝取消，美团取消失败 "+DateUtil.getCurrTime()+"：";
                        StringBuffer dateSb = new StringBuffer();//推送内容
                        dateSb.append("代理通订单号："+switchOrderListNotify.getDltOrderId())
                                .append(" 订单号:"+switchOrderListNotify.getOrderId())
                                .append(" 原因:"+retMap.get("desc"))
                                .append(" 下单时间："+DateUtil.switchTimeParse(switchOrderListNotify.getOrderDate()));
                        SendUtils.dingMsgOrder(title,dateSb.toString(),MessageEnums.genre.REFUDE_ERROR.getCode(),switchOrderListNotify.getOrderId(),restTemplate);
                    }catch (Exception e){
                        log.info("钉钉推送异常，请检查！");
                    }
                }

                //判断如果携程是在15分钟内取消；则所有携程订单都接受取消
                //先根据订单号，获取订单详细信息；为了获取酒店订单创建时间和修改时间
                double dSec = 15*60;//15分钟换算成秒
                double cSec = DateUtil.switchTimeSubtractParse(switchOrderListNotify.getUpdateTime(),switchOrderListNotify.getOrderDate());
                if(dSec >= cSec){//判断如果小于15分钟，状态修改为接受取消
                    switchOrderPool.setSysOrderState(7);//7：接受取消(携程)
                    remarkStr = switchOrderPool.getRemark()+"   携程用户操作订单时间："+switchOrderListNotify.getUpdateTime()+";下单时间："+switchOrderListNotify.getOrderDate()+";两个时间差为(秒)："+cSec;
                }else{
                    //判断相关当前订单的取消规则，是否在最晚取消时间内；如果在最晚取消规则内，可以接受取消；
                    SwitchOrderCancelRules switchOrderCancelRules = new SwitchOrderCancelRules();

                    Example example = new Example(SwitchOrderCancelRules.class);
                    Example.Criteria criteria = example.createCriteria();
                    criteria.andEqualTo("pId",switchOrderPool.getId());
                    example.setOrderByClause(" id limit 1");

                    switchOrderCancelRules = switchOrderCancelRulesMapper.selectOneByExample(example);

                    if(!ObjectUtils.isEmpty(switchOrderCancelRules)){
                        //最晚取消时间 - 订单取消时间
                        double db = DateUtil.switchTimeSubtractParse(switchOrderCancelRules.getLastCancelTime(),switchOrderListNotify.getUpdateTime());
                        if(db>0){
                            switchOrderPool.setSysOrderState(7);//7：接受取消(携程)
//                        switchOrderPool.setRemark(switchOrderPool.getRemark()+"  携程取消规则最晚取消时间："+ switchOrderCancelRules.getLastCancelTime() +" ;  携程用户操作订单时间："+switchOrderListNotify.getUpdateTime()+";下单时间："+switchOrderListNotify.getOrderDate()+";两个时间差为(秒)："+cSec);
                            remarkStr = switchOrderPool.getRemark()+"   携程用户操作订单时间："+switchOrderListNotify.getUpdateTime()+";下单时间："+switchOrderListNotify.getOrderDate()+";两个时间差为(秒)："+cSec;
                        }else{//超过最晚取消时间拒绝取消
                            switchOrderPool.setSysOrderState(8);//8：拒绝取消(携程)
                            remarkStr = switchOrderPool.getRemark()+"   携程用户操作订单时间："+switchOrderListNotify.getUpdateTime()+";下单时间："+switchOrderListNotify.getOrderDate()+";两个时间差为(秒)："+cSec;
//                        switchOrderPool.setRemark(switchOrderPool.getRemark()+"  携程取消规则最晚取消时间："+ switchOrderCancelRules.getLastCancelTime() +" ;  携程用户操作订单时间："+switchOrderListNotify.getUpdateTime()+";下单时间："+switchOrderListNotify.getOrderDate()+";两个时间差为(秒)："+cSec);

                        }
                    }else{//未查询到对应可取消时间默认拒绝取消
                        switchOrderPool.setSysOrderState(8);//8：拒绝取消(携程)
                        remarkStr = switchOrderPool.getRemark()+"  携程取消规则最晚取消时间为空，请检查！  携程用户操作订单时间："+switchOrderListNotify.getUpdateTime()+";下单时间："+switchOrderListNotify.getOrderDate()+";两个时间差为(秒)："+cSec;
//                    switchOrderPool.setRemark(switchOrderPool.getRemark()+"  携程取消规则最晚取消时间为空，请检查！  携程用户操作订单时间："+switchOrderListNotify.getUpdateTime()+";下单时间："+switchOrderListNotify.getOrderDate()+";两个时间差为(秒)："+cSec);
                    }


                }

            }

            log.info("携程订单取消提交 ，返回的操作备注remarkStr --->  {}",remarkStr);
            switchOrderPool.setRemark(remarkStr);

            //version qiuyy  20200907 独立增加pool订单日志保存表
            this.insertPoolStateHistroy(switchOrderPool.getOrderId(),switchOrderPool.getSysOrderState(),
                    switchOrderPool.getMtOrderState(),switchOrderPool.getIsOrder(),DateUtil.getCurrTime()+" cancelNewOperateSwitchAndMeituanOrder:"+remarkStr);

        }


        switchOrderPool.setModifyTime(new Date());//修改时间
        //修改
        log.info("订单池中主键id----->{}",switchOrderPool.getId());
        log.info("订单池中orderId----->{}",switchOrderPool.getOrderId());
        switchOrderPoolMapper.updateOrderResult(switchOrderPool);
        //写入日志
        /*try {
            Thread insertLog=new ThreadInsertLog("携程取消订单状态操作 - cancelNewOperateSwitchAndMeituanOrder",switchOrderPool);
            insertLog.start();
        }catch (Exception logE){
            log.info("写入日志异常，请检查！");
        }*/
        return objectResult;
    }


    /**
     * 携程订单取消操作
     * 先取消美团，再取消携程
     * 2020-09-14
     * 如果美团未采购直接接受取消，并且调用携程操作订单接口
     * @param switchOrderListNotify
     * @param dltOrderId
     * @return
     */
    public Result<Object> cancelNewOperateSwitchAndMeituanOrderNew(SwitchOrderListNotify switchOrderListNotify, String dltOrderId){
        log.info("开始校验订单列表111，携程订单取消操作--cancelNewOperateSwitchAndMeituanOrder>");

        Result<Object> objectResult = new Result<>();
        SwitchOrderPool switchOrderPool = switchOrderPoolMapper.findOrderBySwitchOrderId(switchOrderListNotify.getOrderId());
        log.info("switchOrderPool-->>{}",switchOrderPool);

        //订单备注
        String remarkStr = "";
        //判断美团中是否已下单；如果下单则分为；
//        if(null != switchOrderPool && !ObjectUtils.isEmpty(switchOrderPool.getMeituanOrderId()) ){//美团订单不为空则美团中已提交
        //20200-09-09 18:58 根据携程订单状态(2),美团订单状态(0),是延时单(0) , 说明美团没有下单成功，如果携程推送用户取消订单，则立即接受取消；
        if(ObjectUtils.isEmpty(switchOrderPool) || "0".equals(switchOrderPool.getMtOrderState())  ){
            log.info("美团中没有下单----->");
            String optState = "";//操作新增还是修改
            if(ObjectUtils.isEmpty(switchOrderPool)){//异常订单数据，为做接受订单数据，直接获取到取消订单数据；
                optState = "insert";
                log.info("异常订单数据，为做接受订单数据，直接获取到取消订单数据-->>{}",switchOrderPool);
                switchOrderPool = new SwitchOrderPool();
                switchOrderPool.setId(StringUtil.getUUID());
                switchOrderPool.setCreateTime(new Date());
                switchOrderPool.setState(1);
                switchOrderPool.setRemark("不存在接收订单数据");

            }
            remarkStr = "操作时间："+DateUtil.getNowTime()+ " 美团订单不存在，则未向美团下单，直接接受取消;  "+switchOrderPool.getRemark();
            switchOrderPool.setSysOrderState(7);//7：接受取消(携程)
            switchOrderPool.setMtOrderState("0");//0：美团订单状态修改为0  （2020-09-09 17:10）美团没采购成功，携程那边取消；系统应自动接受取消
            switchOrderPool.setRemark(remarkStr);
            switchOrderPool.setIsOrder(1);//用户取消，立即接受取消
            switchOrderPool.setIsOrderRemark("携程用户取消，立即接受取消");

            if("insert".equals(optState)){//如果订单池不存在当前订单，新增并做接受取消
                switchOrderPoolMapper.insert(switchOrderPool);
            }

            //version qiuyy  20200907 独立增加pool订单日志保存表
            this.insertPoolStateHistroy(switchOrderPool.getOrderId(),switchOrderPool.getSysOrderState(),
                    switchOrderPool.getMtOrderState(),switchOrderPool.getIsOrder(),DateUtil.getCurrTime()+" cancelNewOperateSwitchAndMeituanOrder:"+switchOrderPool.getRemark());


            objectResult.setCode(CommonEnums.MEITUAN_ORDER_DATA_NULL.getCode());
            objectResult.setMsg(remarkStr);

        }else{//正常已向美团下单，做正常取消流程

            log.info("美团中已下单----->");
            //判断美团订单状态是否为 用户已入住：50 ，如果是用户已入住则直接拒绝取消 2020-09-01 修改
            if("50".equals(switchOrderPool.getMtOrderState())){
                remarkStr = "美团订单异步通知用户已入住；状态为：50";
                switchOrderPool.setSysOrderState(8);//8：拒绝取消(携程)
                switchOrderPool.setRemark(remarkStr);
                objectResult.setCode(CommonEnums.MEITUAN_ORDER_CHECK_STATE_IN.getCode());
                objectResult.setMsg(remarkStr);
            }else if("0".equals(switchOrderPool.getMtDistributorOrderId().trim()) || "0".equals(switchOrderPool.getMeituanOrderId().trim())) {//只要是人工采购订单系统不做取消处理，其他渠道采购美团订单号或者分销商订单号为0  2020-12-17 ZhangJZ
                remarkStr = "携程取消，系统订单为人工采购订单；系统不做自动处理";
                log.info("cancelNewOperateSwitchAndMeituanOrderNew-->>switchOrderPool=== {}",JacksonUtil.objectToJson(switchOrderPool));
                switchOrderPool.setRemark(remarkStr);
                objectResult.setCode(CommonEnums.SWITCH_ORDER_CENCAL_OPERATE.getCode());
                objectResult.setMsg(remarkStr);
            }else{
                Map mtHotelOrderCancelParamVo = new HashMap();
                mtHotelOrderCancelParamVo.put("distributorOrderId",switchOrderPool.getMtDistributorOrderId());
                mtHotelOrderCancelParamVo.put("mtOrderId",switchOrderPool.getMeituanOrderId());

                //已下单取消分为：1:待确认取消（直接调用美团取消订单接口；1：未确认预定尝试取消；） 0：正常取消
                if(!switchOrderPool.getMtOrderState().equals(MtHotelEnums.orderStateEnum.BOOKINGSUCCSS.getCode())){//不等于预定成功的数据，则可以直接取消
                    if(switchOrderPool.getMtOrderState().equals(MtHotelEnums.orderStateEnum.BOOKING)){//预定中则取消
                        mtHotelOrderCancelParamVo.put("cancelReason","其它");
                        mtHotelOrderCancelParamVo.put("cancelCheck",1);
                    }else{
                        mtHotelOrderCancelParamVo.put("cancelReason","行程变更");
                        mtHotelOrderCancelParamVo.put("cancelCheck",0);
                    }
                }else{//预定成功，接口会提交正常取消数据，并请走人工客服；
                    mtHotelOrderCancelParamVo.put("cancelReason","行程变更");
                    mtHotelOrderCancelParamVo.put("cancelCheck",0);
                }
                Result<Object> objectCencelResult = new Result<>();
//                Map testMap = new HashMap();
//                testMap.put("code",5);
//                testMap.put("msg","test");
//                objectCencelResult.setData(testMap);

                objectCencelResult = RestTemplateUtils.post(CommonUrlConstants.MEITUAN_HOST+"/mtHotelOrder/orderCancel",JacksonUtil.objectToJson(mtHotelOrderCancelParamVo),restTemplate);
                log.info("objectCencelResult--->>{}",objectCencelResult);
                int countCencel = 0;
                while (countCencel<=3 && ObjectUtils.isEmpty(objectCencelResult.getData())){
                    countCencel++;
                    objectCencelResult = RestTemplateUtils.post(CommonUrlConstants.MEITUAN_HOST+"/mtHotelOrder/orderCancel",JacksonUtil.objectToJson(mtHotelOrderCancelParamVo),restTemplate);
                }
                Map retMap = (Map) objectCencelResult.getData();//解析对象
                switchOrderPool.setRemark(retMap.toString());
                //携程订单取消提交
                /**
                 * 取消订单返回码：
                 * 0 取消成功
                 * 1 系统繁忙
                 * 2 取消失败（超过最晚可取消时间；用户已入住等原因）
                 * 3 订单号不存在
                 * 4 取消失败，产品不允许取消
                 * 5 订单取消中
                 * 10 订单已经确认
                 * 20 其它
                 */
//                if(0 == Integer.valueOf(retMap.get("code").toString())){//返回成功，则取消成功/取消中  20201125更换为以下方式
                if(new BigDecimal(retMap.get("code").toString()).compareTo(new BigDecimal(0)) == 0){//返回成功，则取消成功/取消中
                    switchOrderPool.setSysOrderState(7);//7：接受取消(携程)
                    switchOrderPool.setMtOrderState(String.valueOf(MtHotelEnums.orderStateEnum.CANCELSUCCSS.getCode()));//31：取消成功

                }else if(new BigDecimal(retMap.get("code").toString()).compareTo(new BigDecimal(5)) == 0){//美团取消中，订单池系统状态设置取消中，等待美团异步回调修改状态
//               else if(5 == Integer.valueOf(retMap.get("code").toString())){//美团取消中，订单池系统状态设置取消中，等待美团异步回调修改状态
                    switchOrderPool.setSysOrderState(5);//5：取消中
                    switchOrderPool.setMtOrderState(String.valueOf(MtHotelEnums.orderStateEnum.CANCELING.getCode()));//30：取消中

                }else {//美团取消失败，设置状态为美团取消失败，人工客服联系;原美团订单状态不做变更
                    switchOrderPool.setSysOrderState(8);//8：拒绝取消(携程)
                    switchOrderPool.setMtOrderState(String.valueOf(MtHotelEnums.orderStateEnum.CANCELFAILED.getCode()));//32：取消失败
                    //推送消息至钉钉群,存在异常订单
                    try {
                        String title = "携程取消订单，美团取消失败";
                        StringBuffer dateSb = new StringBuffer();//推送内容
                        dateSb.append("代理通订单号："+switchOrderListNotify.getDltOrderId())
                                .append(" 订单号:"+switchOrderListNotify.getOrderId())
                                .append(" 下单时间："+DateUtil.switchTimeParse(switchOrderListNotify.getOrderDate()))
                                .append(" 美团取消返回值【"+retMap.toString()+"】");
                        SendUtils.dingMsgOrder(title,dateSb.toString(),MessageEnums.genre.REFUDE_ERROR.getCode(),switchOrderListNotify.getOrderId(),restTemplate);
                    }catch (Exception e){
                        log.info("钉钉推送异常，请检查！");
                    }
                }

                //判断如果携程是在15分钟内取消；则所有携程订单都接受取消
                //先根据订单号，获取订单详细信息；为了获取酒店订单创建时间和修改时间
                double dSec = 15*60;//15分钟换算成秒
                double cSec = DateUtil.switchTimeSubtractParse(switchOrderListNotify.getUpdateTime(),switchOrderListNotify.getOrderDate());
                if(dSec >= cSec){//判断如果小于15分钟，状态修改为接受取消
                    switchOrderPool.setSysOrderState(7);//7：接受取消(携程)
                    remarkStr = switchOrderPool.getRemark()+"   携程用户操作订单时间："+switchOrderListNotify.getUpdateTime()+";下单时间："+switchOrderListNotify.getOrderDate()+";两个时间差为(秒)："+cSec;
                }else{
                    //判断相关当前订单的取消规则，是否在最晚取消时间内；如果在最晚取消规则内，可以接受取消；
                    SwitchOrderCancelRules switchOrderCancelRules = new SwitchOrderCancelRules();

                    Example example = new Example(SwitchOrderCancelRules.class);
                    Example.Criteria criteria = example.createCriteria();
                    criteria.andEqualTo("pId",switchOrderPool.getId());
                    example.setOrderByClause(" id limit 1");

                    switchOrderCancelRules = switchOrderCancelRulesMapper.selectOneByExample(example);

                    if(!ObjectUtils.isEmpty(switchOrderCancelRules)){
                        //最晚取消时间 - 订单取消时间
                        double db = DateUtil.switchTimeSubtractParse(switchOrderCancelRules.getLastCancelTime(),switchOrderListNotify.getUpdateTime());
                        if(db>0){
                            switchOrderPool.setSysOrderState(7);//7：接受取消(携程)
                            remarkStr = switchOrderPool.getRemark()+"   携程用户操作订单时间："+switchOrderListNotify.getUpdateTime()+";下单时间："+switchOrderListNotify.getOrderDate()+";两个时间差为(秒)："+cSec;
                        }else{//超过最晚取消时间拒绝取消
                            switchOrderPool.setSysOrderState(8);//8：拒绝取消(携程)
                            remarkStr = switchOrderPool.getRemark()+"   携程用户操作订单时间："+switchOrderListNotify.getUpdateTime()+";下单时间："+switchOrderListNotify.getOrderDate()+";两个时间差为(秒)："+cSec;

                        }
                    }else{//未查询到对应可取消时间默认拒绝取消
                        switchOrderPool.setSysOrderState(8);//8：拒绝取消(携程)
                        remarkStr = switchOrderPool.getRemark()+"  携程取消规则最晚取消时间为空，请检查！  携程用户操作订单时间："+switchOrderListNotify.getUpdateTime()+";下单时间："+switchOrderListNotify.getOrderDate()+";两个时间差为(秒)："+cSec;
                    }


                }

            }

            log.info("携程订单取消提交 ，返回的操作备注remarkStr --->  {}",remarkStr);
            switchOrderPool.setRemark(remarkStr);

            //version qiuyy  20200907 独立增加pool订单日志保存表
            this.insertPoolStateHistroy(switchOrderPool.getOrderId(),switchOrderPool.getSysOrderState(),
                    switchOrderPool.getMtOrderState(),switchOrderPool.getIsOrder(),DateUtil.getCurrTime()+" cancelNewOperateSwitchAndMeituanOrder:"+remarkStr);
            objectResult.setCode(CommonConstants.SUCCESS);
            objectResult.setMsg(remarkStr);
        }


        switchOrderPool.setModifyTime(new Date());//修改时间
        //修改
        switchOrderPoolMapper.updateOrderResult(switchOrderPool);

        objectResult.setData(switchOrderPool);
        return objectResult;
    }
    /***
    * @Author: lmf
    * @Date: 2020/9/25
     * 统计接单时长
    */
    @Override
    public Result<Object> getOrderList(OrderInfoVo orderInfoVo) {
        PageHelper.startPage(orderInfoVo.getPageCode(), orderInfoVo.getPageSize());
        List<SwitchOrderInfoVo> list = switchOrderInfoMapper.getOrderList(orderInfoVo);;
        PageInfo<SwitchOrderInfoVo> pageInfo = new PageInfo<>(list);
        return new Result<>(pageInfo);
    }
    /***
    * @Author: lmf
    * @Date: 2020/9/27
     * 查看酒店的订单列表
    */
    @Override
    public Result<Object> orderHotelList(OrderInfoVo orderInfoVo) {
        PageHelper.startPage(orderInfoVo.getPageCode(), orderInfoVo.getPageSize());
        List<SwitchOrderInfoVo> list = switchOrderInfoMapper.orderHotelList(orderInfoVo);;
        PageInfo<SwitchOrderInfoVo> pageInfo = new PageInfo<>(list);
        return new Result<>(pageInfo);
    }

    /****************************************************操作订单流程   ending*******************************************************************/


class ThreadDingMessage extends Thread{
    private SwitchOrderListNotify switchOrderListNotify;
    public ThreadDingMessage(SwitchOrderListNotify switchOrderListNotify) {
        this.switchOrderListNotify = switchOrderListNotify;
    }

    @Override
    public void run() {
        log.info("进入钉钉消息通知：");
        try {
            Thread.sleep(5);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        SwitchOrderPool switchOrderPool = switchOrderPoolMapper.findOrderBySwitchOrderId(switchOrderListNotify.getOrderId());
        //判断是否存在当前订单，不存在则说明是新订单
        String title = "";//推送主题

        //判断是否亏损单
        boolean hasProfit = true;
        StringBuffer dateSb = new StringBuffer();//推送内容
        int type = 0;//类型
        if("N".equals(switchOrderListNotify.getFormType()) && "0".equals(switchOrderListNotify.getOrderStatus())){
            title = "您有新订单了";
            dateSb.append(DateUtil.getCurrTime()+" 代理通订单号："+switchOrderListNotify.getDltOrderId())
                    .append(" 订单号:"+switchOrderListNotify.getOrderId())
                    .append(" 下单时间："+DateUtil.switchTimeParse(switchOrderListNotify.getOrderDate()))
                    .append(" 入住时间："+DateUtil.switchTimeParse(switchOrderListNotify.getCheckinDate()))
                    .append(" 离店时间："+DateUtil.switchTimeParse(switchOrderListNotify.getCheckoutDate()));
        }else if("C".equals(switchOrderListNotify.getFormType()) && "0".equals(switchOrderListNotify.getOrderStatus())){//取消订单,未操作
            type = MessageEnums.genre.REFUDE_ERROR.getCode();
            title = "用户取消了订单 "+DateUtil.getCurrTime()+"：";
            dateSb.append("代理通订单号："+switchOrderListNotify.getDltOrderId())
                    .append(" 订单号:"+switchOrderListNotify.getOrderId())
                    .append(" 下单时间："+DateUtil.switchTimeParse(switchOrderListNotify.getOrderDate()));
        }else if(!"N".equals(switchOrderListNotify.getFormType()) && !"C".equals(switchOrderListNotify.getFormType()) && !"T".equals(switchOrderListNotify.getFormType())){
            type = 4;
            title = "携程异常订单,请及时处理 "+DateUtil.getCurrTime()+"：";
            dateSb.append("代理通订单号："+switchOrderListNotify.getDltOrderId())
                    .append(" 订单号:"+switchOrderListNotify.getOrderId())
                    .append(" 下单时间："+DateUtil.switchTimeParse(switchOrderListNotify.getOrderDate()));
        }else if("T".equals(switchOrderListNotify.getFormType()) ){
            type = 4;
            title = "携程无效订单(已处理的订单)！ "+DateUtil.getCurrTime()+"：";
            dateSb.append("代理通订单号："+switchOrderListNotify.getDltOrderId())
                    .append(" 订单号:"+switchOrderListNotify.getOrderId())
                    .append(" 下单时间："+DateUtil.switchTimeParse(switchOrderListNotify.getOrderDate()));
        }else if("D".equals(switchOrderListNotify.getFormType()) && "0".equals(switchOrderListNotify.getOrderStatus())){
            title = "您有新订单了(延住)";
            dateSb.append(DateUtil.getCurrTime()+" 代理通订单号："+switchOrderListNotify.getDltOrderId())
                    .append(" 订单号:"+switchOrderListNotify.getOrderId())
                    .append(" 下单时间："+DateUtil.switchTimeParse(switchOrderListNotify.getOrderDate()))
                    .append(" 入住时间："+DateUtil.switchTimeParse(switchOrderListNotify.getCheckinDate()))
                    .append(" 离店时间："+DateUtil.switchTimeParse(switchOrderListNotify.getCheckoutDate()));
        }else if("N".equals(switchOrderListNotify.getFormType()) && "100".equals(switchOrderListNotify.getOrderStatus())){
//            hasProfit = getHasProfitByOrderId(switchOrderListNotify.getOrderId());
            //是否盈利 true 盈利；false ：亏损
//            if(hasProfit){
//                type = MessageEnums.genre.ORDER_SUCCESS.getCode();
//            }else{
//                type = 9;
//            }
            type = 8;
            title = "您有新订单，携程已接单了！";//通知给投资人看的群
            dateSb.append(DateUtil.getCurrTime()+" 代理通订单号："+switchOrderListNotify.getDltOrderId())
                    .append(" 订单号:"+switchOrderListNotify.getOrderId())
                    .append(" 下单时间："+DateUtil.switchTimeParse(switchOrderListNotify.getOrderDate()))
                    .append(" 入住时间："+DateUtil.switchTimeParse(switchOrderListNotify.getCheckinDate()))
                    .append(" 离店时间："+DateUtil.switchTimeParse(switchOrderListNotify.getCheckoutDate()));
        }else if("D".equals(switchOrderListNotify.getFormType()) && "100".equals(switchOrderListNotify.getOrderStatus())){
//            hasProfit = getHasProfitByOrderId(switchOrderListNotify.getOrderId());
            //是否盈利 true 盈利；false ：亏损
//            if(hasProfit){
                type = 8;
//            }else{
//                type = 9;
//            }
            title = "您有新订单了(延住)，携程已接单了！";//通知给投资人看的群
            dateSb.append(DateUtil.getCurrTime()+" 代理通订单号："+switchOrderListNotify.getDltOrderId())
                    .append(" 订单号:"+switchOrderListNotify.getOrderId())
                    .append(" 下单时间："+DateUtil.switchTimeParse(switchOrderListNotify.getOrderDate()))
                    .append(" 入住时间："+DateUtil.switchTimeParse(switchOrderListNotify.getCheckinDate()))
                    .append(" 离店时间："+DateUtil.switchTimeParse(switchOrderListNotify.getCheckoutDate()));
        }else if("C".equals(switchOrderListNotify.getFormType()) && "100".equals(switchOrderListNotify.getOrderStatus())){
//            type = 8;//
            type = MessageEnums.genre.REFUDE_ERROR.getCode();
            title = "用户取消了订单,取消成功！";//通知给投资人看的群
            dateSb.append(DateUtil.getCurrTime()+" 代理通订单号："+switchOrderListNotify.getDltOrderId())
                    .append(" 订单号:"+switchOrderListNotify.getOrderId())
                    .append(" 下单时间："+DateUtil.switchTimeParse(switchOrderListNotify.getOrderDate()))
                    .append(" 入住时间："+DateUtil.switchTimeParse(switchOrderListNotify.getCheckinDate()))
                    .append(" 离店时间："+DateUtil.switchTimeParse(switchOrderListNotify.getCheckoutDate()));
        }
        if(!ObjectUtils.isEmpty(title)){
            try{
                SendUtils.dingMsgOrder(title,dateSb.toString(),type,switchOrderListNotify.getOrderId(),restTemplate);
            }catch (Exception e){
                log.info("switchOrderInfo-->>> 推送订单通知至钉钉 异常！！！");
            }

            log.info("推送订单通知至钉钉 title:"+title+"; data:{"+dateSb.toString()+"}; type:"+type);
        }
    }

}
    /**
     * 判断是否盈利
     * @param orderId
     * @return
     */
    public boolean getHasProfitByOrderId(String orderId){
        //是否盈利默认 true
        boolean ret = true;
        //获取美团订单总价
        int mtOrderPrice = 0;
        //获取携程订单总价
        int swOrderPrice = 0;
        //调用美团接口查询美团订单信息
        Map<String,Object> map = new HashMap();
        map.put("swOrder",orderId);
        Result hasRet = RestTemplateUtils.get(CommonUrlConstants.MEITUAN_HOST+"/mtHotelOrder/selectOneBySwOrderIsVail",map,restTemplate);
        if(hasRet.getCode() == CommonConstants.SUCCESS){
            Map retMap = new HashMap();
            retMap = JacksonUtil.parse(JacksonUtil.objectToJson(hasRet.getData()),Map.class);
            if(!ObjectUtils.isEmpty(retMap) && retMap.size()>0){
                //获取美团采购价
                mtOrderPrice = Integer.valueOf(retMap.get("mtSettlePrice").toString());
            }
        }else{
            return ret;
        }

        log.info("mtOrderPrice 美团采购价>>>{}");

        Map swoMap = new HashMap();
        swoMap.put("orderId",orderId);
        SwitchOrderInfo switchOrderInfo = switchOrderInfoMapper.findOneByOrderId(swoMap);
        if(!ObjectUtils.isEmpty(switchOrderInfo)){
            swOrderPrice = switchOrderInfo.getOrderPrice().multiply(new BigDecimal(100)).intValue();
        }

        //如果携程价格小于美团的采购价，则说明亏损
        if(mtOrderPrice>swOrderPrice){
            ret = false;
        }

        return ret;
    }

    /**
     * 订单日志操作
     * @param optRemark 操作备注
     * @param object 对象
     */
    public void insertLog(String optRemark,Object object){
//        String access_token = HttpClientBaseAuth.getAuthToken();
        /*try{
            String adminUrl= CommonUrlConstants.ADMIN_HOST+"/"+ AdminRequestUrlEnums.API_LOG.getUrl();//+"?access_token="+access_token;
            Map<String,Object> params=new HashMap<>();
            params.put("systemName","switch_order");
            params.put("className",this.getClass().getName());
            params.put("remark",optRemark);
            params.put("json",JacksonUtil.objectToJson(object));
            switchRestTempaleUtilsService.sendPostRequestToAdmin(adminUrl,params);
        }catch (Exception e){
            log.info("===============请求  admin - 日志接口模块异常=====================");
        }*/

    }


    class ThreadInsertLog extends Thread{
        private Object object;
        private String optRemark;
        public ThreadInsertLog(String optRemark,Object object) {
            this.object = object;
            this.optRemark = optRemark;
        }

        @Override
        public void run() {
            log.info("进入携程订单状态操作日志：");
            try {
                Thread.sleep(300);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            insertLog(optRemark,object);
        }

    }
    /***
     * @Author: lmf
     * @Date: 2021/4/15
     */
    @Override
    public Result<Object> statisOrderNum() {
        Integer num=switchOrderInfoMapper.statisOrderNum();
        return new Result<>(num);
    }
    /***
     * @Author: lmf
     * @Date: 2021/4/29
     * 获取订单的信息
     */
    @Override
    public Result<Object> getOrderRoomInfo(String orderId) {
        return null;
    }
}
